<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>AJ</title>
    <meta name="generator" content="VuePress 1.5.0">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <script>
            var _hmt = _hmt || [];
            (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?51b8c2e72d1adf96524638ce85bb7d72";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);

            // 引入谷歌,不需要可删除这段
            var hm1 = document.createElement("script");
            hm1.src = "https://www.googletagmanager.com/gtag/js?id=G-B7351EYS04";
            var s1 = document.getElementsByTagName("script")[0]; 
            s1.parentNode.insertBefore(hm1, s1);
            })();

            // 谷歌加载,不需要可删除
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', 'G-B7351EYS04');
        </script>
    <meta name="description" content="阿俊博客|记录一个程序员的成长历程 阿俊博客(blog.zhequtao.com)记录一个后端程序员的成长历程,分享他的学习笔记和心得,还有些开发必备技巧哦! java golang web html dev开发">
    <link rel="preload" href="/assets/css/0.styles.a3df589e.css" as="style"><link rel="preload" href="/assets/js/app.cb35c8f6.js" as="script"><link rel="preload" href="/assets/js/2.063846a6.js" as="script"><link rel="preload" href="/assets/js/4.1ffb4609.js" as="script"><link rel="preload" href="/assets/js/6.29d112b1.js" as="script"><link rel="prefetch" href="/assets/js/10.5629fe4d.js"><link rel="prefetch" href="/assets/js/100.8417ccea.js"><link rel="prefetch" href="/assets/js/101.37fdb377.js"><link rel="prefetch" href="/assets/js/102.848b686d.js"><link rel="prefetch" href="/assets/js/103.6a2489a0.js"><link rel="prefetch" href="/assets/js/104.99e8899f.js"><link rel="prefetch" href="/assets/js/105.8b741763.js"><link rel="prefetch" href="/assets/js/106.08163715.js"><link rel="prefetch" href="/assets/js/107.21801349.js"><link rel="prefetch" href="/assets/js/108.e3a2892b.js"><link rel="prefetch" href="/assets/js/109.dab5618c.js"><link rel="prefetch" href="/assets/js/11.cddc1623.js"><link rel="prefetch" href="/assets/js/110.f5249b39.js"><link rel="prefetch" href="/assets/js/111.9abf8bce.js"><link rel="prefetch" href="/assets/js/112.8eb86924.js"><link rel="prefetch" href="/assets/js/113.c180ed46.js"><link rel="prefetch" href="/assets/js/114.2370f5b5.js"><link rel="prefetch" href="/assets/js/115.88dc3fd8.js"><link rel="prefetch" href="/assets/js/116.63403600.js"><link rel="prefetch" href="/assets/js/117.83674aa0.js"><link rel="prefetch" href="/assets/js/118.9c58c685.js"><link rel="prefetch" href="/assets/js/119.621f9a70.js"><link rel="prefetch" href="/assets/js/12.ff3d03f5.js"><link rel="prefetch" href="/assets/js/120.a6d2b7f7.js"><link rel="prefetch" href="/assets/js/121.ae0ce9d1.js"><link rel="prefetch" href="/assets/js/122.de240e6d.js"><link rel="prefetch" href="/assets/js/123.b043e3e4.js"><link rel="prefetch" href="/assets/js/124.550af937.js"><link rel="prefetch" href="/assets/js/125.6f06b34c.js"><link rel="prefetch" href="/assets/js/126.38d64604.js"><link rel="prefetch" href="/assets/js/127.a948db56.js"><link rel="prefetch" href="/assets/js/128.4ca789e0.js"><link rel="prefetch" href="/assets/js/129.59be4505.js"><link rel="prefetch" href="/assets/js/13.e9f75cc3.js"><link rel="prefetch" href="/assets/js/130.ddae76a9.js"><link rel="prefetch" href="/assets/js/131.d969c265.js"><link rel="prefetch" href="/assets/js/132.5f43ce5c.js"><link rel="prefetch" href="/assets/js/133.b651af22.js"><link rel="prefetch" href="/assets/js/134.2499236a.js"><link rel="prefetch" href="/assets/js/135.4180596c.js"><link rel="prefetch" href="/assets/js/136.2c309233.js"><link rel="prefetch" href="/assets/js/137.72ca42dd.js"><link rel="prefetch" href="/assets/js/138.3772cd38.js"><link rel="prefetch" href="/assets/js/139.1d0a53da.js"><link rel="prefetch" href="/assets/js/14.be4b89ed.js"><link rel="prefetch" href="/assets/js/140.22368353.js"><link rel="prefetch" href="/assets/js/141.a14aef3c.js"><link rel="prefetch" href="/assets/js/142.2041ce3a.js"><link rel="prefetch" href="/assets/js/143.377262ec.js"><link rel="prefetch" href="/assets/js/144.8fcbc368.js"><link rel="prefetch" href="/assets/js/145.46da36bf.js"><link rel="prefetch" href="/assets/js/146.eceae0d9.js"><link rel="prefetch" href="/assets/js/147.e1bd6531.js"><link rel="prefetch" href="/assets/js/148.76f193ce.js"><link rel="prefetch" href="/assets/js/149.587bd581.js"><link rel="prefetch" href="/assets/js/15.e3219ac0.js"><link rel="prefetch" href="/assets/js/150.169c71e0.js"><link rel="prefetch" href="/assets/js/151.384021ea.js"><link rel="prefetch" href="/assets/js/152.0f20cf03.js"><link rel="prefetch" href="/assets/js/153.fd94af1e.js"><link rel="prefetch" href="/assets/js/154.a550f5dc.js"><link rel="prefetch" href="/assets/js/155.ba1ae86e.js"><link rel="prefetch" href="/assets/js/156.3b98ded0.js"><link rel="prefetch" href="/assets/js/157.cd378596.js"><link rel="prefetch" href="/assets/js/158.c138d0df.js"><link rel="prefetch" href="/assets/js/159.2635f7f4.js"><link rel="prefetch" href="/assets/js/16.c9c35d42.js"><link rel="prefetch" href="/assets/js/160.d51b4126.js"><link rel="prefetch" href="/assets/js/161.5dc29e7b.js"><link rel="prefetch" href="/assets/js/162.f257a92b.js"><link rel="prefetch" href="/assets/js/163.9eb75e40.js"><link rel="prefetch" href="/assets/js/164.8fb1e22b.js"><link rel="prefetch" href="/assets/js/165.49255503.js"><link rel="prefetch" href="/assets/js/166.e54539e6.js"><link rel="prefetch" href="/assets/js/167.a06acdb0.js"><link rel="prefetch" href="/assets/js/168.948ab620.js"><link rel="prefetch" href="/assets/js/169.7d756812.js"><link rel="prefetch" href="/assets/js/17.81067bc8.js"><link rel="prefetch" href="/assets/js/170.ffe63330.js"><link rel="prefetch" href="/assets/js/171.835398b9.js"><link rel="prefetch" href="/assets/js/172.3987be39.js"><link rel="prefetch" href="/assets/js/173.e3cedb8a.js"><link rel="prefetch" href="/assets/js/174.11a32588.js"><link rel="prefetch" href="/assets/js/175.da6f9782.js"><link rel="prefetch" href="/assets/js/176.50e55edc.js"><link rel="prefetch" href="/assets/js/177.a89a1d17.js"><link rel="prefetch" href="/assets/js/178.7ad3ce84.js"><link rel="prefetch" href="/assets/js/179.98a1343b.js"><link rel="prefetch" href="/assets/js/18.b67caf4c.js"><link rel="prefetch" href="/assets/js/180.4e98599b.js"><link rel="prefetch" href="/assets/js/181.dd885afd.js"><link rel="prefetch" href="/assets/js/182.789990c8.js"><link rel="prefetch" href="/assets/js/183.f11ca2fd.js"><link rel="prefetch" href="/assets/js/184.fcf128ec.js"><link rel="prefetch" href="/assets/js/185.54e1e9b6.js"><link rel="prefetch" href="/assets/js/186.db91021a.js"><link rel="prefetch" href="/assets/js/187.5309dd42.js"><link rel="prefetch" href="/assets/js/188.615821ea.js"><link rel="prefetch" href="/assets/js/189.f23f1d42.js"><link rel="prefetch" href="/assets/js/19.294a011c.js"><link rel="prefetch" href="/assets/js/190.efe894bc.js"><link rel="prefetch" href="/assets/js/191.0d14904a.js"><link rel="prefetch" href="/assets/js/192.efd25a9e.js"><link rel="prefetch" href="/assets/js/193.88151f34.js"><link rel="prefetch" href="/assets/js/194.efedce14.js"><link rel="prefetch" href="/assets/js/195.03ac15bb.js"><link rel="prefetch" href="/assets/js/196.fbc18389.js"><link rel="prefetch" href="/assets/js/197.0257ab5e.js"><link rel="prefetch" href="/assets/js/198.f1de2817.js"><link rel="prefetch" href="/assets/js/199.8f1c166b.js"><link rel="prefetch" href="/assets/js/20.1a41edb1.js"><link rel="prefetch" href="/assets/js/200.4af99727.js"><link rel="prefetch" href="/assets/js/201.9f8caef1.js"><link rel="prefetch" href="/assets/js/202.6f07d705.js"><link rel="prefetch" href="/assets/js/203.5012fe50.js"><link rel="prefetch" href="/assets/js/204.3a0dfd8e.js"><link rel="prefetch" href="/assets/js/205.0ba9b606.js"><link rel="prefetch" href="/assets/js/206.663a49ec.js"><link rel="prefetch" href="/assets/js/207.b2406149.js"><link rel="prefetch" href="/assets/js/208.b0b2dfd8.js"><link rel="prefetch" href="/assets/js/209.41a0ec9f.js"><link rel="prefetch" href="/assets/js/21.b6ea6f9a.js"><link rel="prefetch" href="/assets/js/210.6f36beb8.js"><link rel="prefetch" href="/assets/js/211.90ef6e5c.js"><link rel="prefetch" href="/assets/js/212.42339063.js"><link rel="prefetch" href="/assets/js/213.a2bfeda9.js"><link rel="prefetch" href="/assets/js/214.5c7eb42a.js"><link rel="prefetch" href="/assets/js/215.18260ae5.js"><link rel="prefetch" href="/assets/js/216.7678fd29.js"><link rel="prefetch" href="/assets/js/217.9d936f88.js"><link rel="prefetch" href="/assets/js/218.bac403c4.js"><link rel="prefetch" href="/assets/js/219.9d8cb16b.js"><link rel="prefetch" href="/assets/js/22.367cc253.js"><link rel="prefetch" href="/assets/js/220.375b7707.js"><link rel="prefetch" href="/assets/js/221.3e400da4.js"><link rel="prefetch" href="/assets/js/222.8fbd2857.js"><link rel="prefetch" href="/assets/js/223.76a10075.js"><link rel="prefetch" href="/assets/js/224.ff94cc4e.js"><link rel="prefetch" href="/assets/js/225.d4688ca6.js"><link rel="prefetch" href="/assets/js/226.b13b18af.js"><link rel="prefetch" href="/assets/js/227.288d0f96.js"><link rel="prefetch" href="/assets/js/228.60430ac0.js"><link rel="prefetch" href="/assets/js/229.da728342.js"><link rel="prefetch" href="/assets/js/23.bc3de730.js"><link rel="prefetch" href="/assets/js/230.d8417d20.js"><link rel="prefetch" href="/assets/js/231.6a9ce0b4.js"><link rel="prefetch" href="/assets/js/232.7611b413.js"><link rel="prefetch" href="/assets/js/233.94712cf9.js"><link rel="prefetch" href="/assets/js/234.93888298.js"><link rel="prefetch" href="/assets/js/235.62506981.js"><link rel="prefetch" href="/assets/js/236.5a055c7c.js"><link rel="prefetch" href="/assets/js/237.0a6c4902.js"><link rel="prefetch" href="/assets/js/238.e5f37663.js"><link rel="prefetch" href="/assets/js/239.331bba86.js"><link rel="prefetch" href="/assets/js/24.82f0901c.js"><link rel="prefetch" href="/assets/js/240.59591cfc.js"><link rel="prefetch" href="/assets/js/241.ce671f47.js"><link rel="prefetch" href="/assets/js/242.fb2542fa.js"><link rel="prefetch" href="/assets/js/243.74abc73d.js"><link rel="prefetch" href="/assets/js/244.ecd707b2.js"><link rel="prefetch" href="/assets/js/245.d728367b.js"><link rel="prefetch" href="/assets/js/246.9270e7fe.js"><link rel="prefetch" href="/assets/js/247.a421ba15.js"><link rel="prefetch" href="/assets/js/248.e759132e.js"><link rel="prefetch" href="/assets/js/249.3077fb46.js"><link rel="prefetch" href="/assets/js/25.95c551dc.js"><link rel="prefetch" href="/assets/js/250.5fe4dd03.js"><link rel="prefetch" href="/assets/js/251.4b8fe76c.js"><link rel="prefetch" href="/assets/js/252.0d1cf7ea.js"><link rel="prefetch" href="/assets/js/253.89d16ba0.js"><link rel="prefetch" href="/assets/js/254.8d1afc68.js"><link rel="prefetch" href="/assets/js/255.64e680cb.js"><link rel="prefetch" href="/assets/js/256.9defbd0e.js"><link rel="prefetch" href="/assets/js/257.1fef24fd.js"><link rel="prefetch" href="/assets/js/258.4e205286.js"><link rel="prefetch" href="/assets/js/259.f3d56efc.js"><link rel="prefetch" href="/assets/js/26.7fe56bac.js"><link rel="prefetch" href="/assets/js/260.378299e6.js"><link rel="prefetch" href="/assets/js/261.8e4fb397.js"><link rel="prefetch" href="/assets/js/262.54595d98.js"><link rel="prefetch" href="/assets/js/263.fb333dc1.js"><link rel="prefetch" href="/assets/js/264.13d13301.js"><link rel="prefetch" href="/assets/js/265.c85104bc.js"><link rel="prefetch" href="/assets/js/266.9f3d1f1c.js"><link rel="prefetch" href="/assets/js/267.fb392815.js"><link rel="prefetch" href="/assets/js/268.add7eacb.js"><link rel="prefetch" href="/assets/js/269.7e49fcc7.js"><link rel="prefetch" href="/assets/js/27.5547e5f0.js"><link rel="prefetch" href="/assets/js/270.22342070.js"><link rel="prefetch" href="/assets/js/271.59917b1a.js"><link rel="prefetch" href="/assets/js/272.4a4751d5.js"><link rel="prefetch" href="/assets/js/273.f4c2fa5c.js"><link rel="prefetch" href="/assets/js/274.1208bc94.js"><link rel="prefetch" href="/assets/js/275.f6528753.js"><link rel="prefetch" href="/assets/js/276.a68772cd.js"><link rel="prefetch" href="/assets/js/277.f154ab32.js"><link rel="prefetch" href="/assets/js/278.bb616a63.js"><link rel="prefetch" href="/assets/js/279.6a356cff.js"><link rel="prefetch" href="/assets/js/28.b08b2847.js"><link rel="prefetch" href="/assets/js/280.5afc20fc.js"><link rel="prefetch" href="/assets/js/281.3cd86225.js"><link rel="prefetch" href="/assets/js/282.3ecb92aa.js"><link rel="prefetch" href="/assets/js/283.85159ea7.js"><link rel="prefetch" href="/assets/js/284.b6545c68.js"><link rel="prefetch" href="/assets/js/285.5e83ee29.js"><link rel="prefetch" href="/assets/js/286.2aad298d.js"><link rel="prefetch" href="/assets/js/287.3ca76244.js"><link rel="prefetch" href="/assets/js/288.5b17963d.js"><link rel="prefetch" href="/assets/js/289.f47a759b.js"><link rel="prefetch" href="/assets/js/29.562dbf7d.js"><link rel="prefetch" href="/assets/js/290.36b603c7.js"><link rel="prefetch" href="/assets/js/291.a9bd8951.js"><link rel="prefetch" href="/assets/js/292.dfc54f28.js"><link rel="prefetch" href="/assets/js/293.2d061212.js"><link rel="prefetch" href="/assets/js/294.6d564a9e.js"><link rel="prefetch" href="/assets/js/295.a31dd593.js"><link rel="prefetch" href="/assets/js/296.3101e5e8.js"><link rel="prefetch" href="/assets/js/297.7efde936.js"><link rel="prefetch" href="/assets/js/298.8bb3aa68.js"><link rel="prefetch" href="/assets/js/299.8b51e6bd.js"><link rel="prefetch" href="/assets/js/3.76257eb7.js"><link rel="prefetch" href="/assets/js/30.221adea2.js"><link rel="prefetch" href="/assets/js/300.62effe45.js"><link rel="prefetch" href="/assets/js/301.98c863c5.js"><link rel="prefetch" href="/assets/js/302.e3493ab2.js"><link rel="prefetch" href="/assets/js/303.800c8028.js"><link rel="prefetch" href="/assets/js/304.b6f08986.js"><link rel="prefetch" href="/assets/js/305.09af356b.js"><link rel="prefetch" href="/assets/js/306.d0d3589d.js"><link rel="prefetch" href="/assets/js/307.ee2fd249.js"><link rel="prefetch" href="/assets/js/308.f3f76368.js"><link rel="prefetch" href="/assets/js/309.d2b5ce40.js"><link rel="prefetch" href="/assets/js/31.334fc8bb.js"><link rel="prefetch" href="/assets/js/310.b4fa2feb.js"><link rel="prefetch" href="/assets/js/311.7d747ef3.js"><link rel="prefetch" href="/assets/js/312.89bdff40.js"><link rel="prefetch" href="/assets/js/313.875b82fe.js"><link rel="prefetch" href="/assets/js/314.0bbe51c4.js"><link rel="prefetch" href="/assets/js/315.cc07dbcf.js"><link rel="prefetch" href="/assets/js/316.bc72b152.js"><link rel="prefetch" href="/assets/js/317.55462812.js"><link rel="prefetch" href="/assets/js/318.a158fda0.js"><link rel="prefetch" href="/assets/js/319.b03a5bd2.js"><link rel="prefetch" href="/assets/js/32.d6826b16.js"><link rel="prefetch" href="/assets/js/320.a5bd19b0.js"><link rel="prefetch" href="/assets/js/321.4f9faaa7.js"><link rel="prefetch" href="/assets/js/322.dbd3b4fa.js"><link rel="prefetch" href="/assets/js/323.a04e2062.js"><link rel="prefetch" href="/assets/js/324.c45b46cf.js"><link rel="prefetch" href="/assets/js/325.cd1460c4.js"><link rel="prefetch" href="/assets/js/326.bd90ef85.js"><link rel="prefetch" href="/assets/js/327.8bf38ef7.js"><link rel="prefetch" href="/assets/js/328.99e9aed3.js"><link rel="prefetch" href="/assets/js/329.de0012cb.js"><link rel="prefetch" href="/assets/js/33.b1059062.js"><link rel="prefetch" href="/assets/js/330.59f11391.js"><link rel="prefetch" href="/assets/js/331.6d16a13c.js"><link rel="prefetch" href="/assets/js/332.922ca235.js"><link rel="prefetch" href="/assets/js/333.c94c3602.js"><link rel="prefetch" href="/assets/js/334.77e02010.js"><link rel="prefetch" href="/assets/js/335.1e0c4f7b.js"><link rel="prefetch" href="/assets/js/336.5675dc4f.js"><link rel="prefetch" href="/assets/js/337.bb6e11dc.js"><link rel="prefetch" href="/assets/js/338.294981e9.js"><link rel="prefetch" href="/assets/js/339.d0376372.js"><link rel="prefetch" href="/assets/js/34.0c7d5782.js"><link rel="prefetch" href="/assets/js/340.64596428.js"><link rel="prefetch" href="/assets/js/341.ec0f9409.js"><link rel="prefetch" href="/assets/js/342.7abc47c4.js"><link rel="prefetch" href="/assets/js/343.4262d486.js"><link rel="prefetch" href="/assets/js/344.8729ad8c.js"><link rel="prefetch" href="/assets/js/345.c210d888.js"><link rel="prefetch" href="/assets/js/346.6f42f7cb.js"><link rel="prefetch" href="/assets/js/347.81b41ae5.js"><link rel="prefetch" href="/assets/js/348.07eca37c.js"><link rel="prefetch" href="/assets/js/349.8019d6f3.js"><link rel="prefetch" href="/assets/js/35.ae14e37f.js"><link rel="prefetch" href="/assets/js/350.57da2e7b.js"><link rel="prefetch" href="/assets/js/351.2e99afdf.js"><link rel="prefetch" href="/assets/js/352.67dd88b7.js"><link rel="prefetch" href="/assets/js/353.15b9f624.js"><link rel="prefetch" href="/assets/js/354.a63e8432.js"><link rel="prefetch" href="/assets/js/355.bbc16ee9.js"><link rel="prefetch" href="/assets/js/356.ff63d3bb.js"><link rel="prefetch" href="/assets/js/357.4fb2d941.js"><link rel="prefetch" href="/assets/js/358.55182977.js"><link rel="prefetch" href="/assets/js/359.265c3d26.js"><link rel="prefetch" href="/assets/js/36.b9ed4cf1.js"><link rel="prefetch" href="/assets/js/360.ced80eb3.js"><link rel="prefetch" href="/assets/js/361.afe6ba84.js"><link rel="prefetch" href="/assets/js/362.c2b62518.js"><link rel="prefetch" href="/assets/js/363.0c4a4800.js"><link rel="prefetch" href="/assets/js/364.ce60291b.js"><link rel="prefetch" href="/assets/js/365.0e3a61f9.js"><link rel="prefetch" href="/assets/js/366.d53ccb03.js"><link rel="prefetch" href="/assets/js/367.689e464d.js"><link rel="prefetch" href="/assets/js/368.418c571f.js"><link rel="prefetch" href="/assets/js/369.c2fff3c8.js"><link rel="prefetch" href="/assets/js/37.a021ac57.js"><link rel="prefetch" href="/assets/js/370.a932b958.js"><link rel="prefetch" href="/assets/js/371.7d153241.js"><link rel="prefetch" href="/assets/js/372.fb9878fa.js"><link rel="prefetch" href="/assets/js/373.85772e03.js"><link rel="prefetch" href="/assets/js/374.b4a8b1b6.js"><link rel="prefetch" href="/assets/js/375.32f70596.js"><link rel="prefetch" href="/assets/js/376.a16d79a8.js"><link rel="prefetch" href="/assets/js/377.c996b7e1.js"><link rel="prefetch" href="/assets/js/378.d37d15c7.js"><link rel="prefetch" href="/assets/js/379.b81ba7dd.js"><link rel="prefetch" href="/assets/js/38.89138658.js"><link rel="prefetch" href="/assets/js/380.524c9b31.js"><link rel="prefetch" href="/assets/js/381.7ebfd6db.js"><link rel="prefetch" href="/assets/js/382.29edda0f.js"><link rel="prefetch" href="/assets/js/383.9642a212.js"><link rel="prefetch" href="/assets/js/384.086e3b42.js"><link rel="prefetch" href="/assets/js/385.a9bb46a8.js"><link rel="prefetch" href="/assets/js/386.f2561a39.js"><link rel="prefetch" href="/assets/js/387.ba9b6aaa.js"><link rel="prefetch" href="/assets/js/388.e0ace495.js"><link rel="prefetch" href="/assets/js/389.ba8c09dd.js"><link rel="prefetch" href="/assets/js/39.04f331e3.js"><link rel="prefetch" href="/assets/js/390.de1bb48b.js"><link rel="prefetch" href="/assets/js/391.7cc6edeb.js"><link rel="prefetch" href="/assets/js/392.0493a6f7.js"><link rel="prefetch" href="/assets/js/393.ba2d3e62.js"><link rel="prefetch" href="/assets/js/394.b3aa9224.js"><link rel="prefetch" href="/assets/js/395.f4df3a60.js"><link rel="prefetch" href="/assets/js/396.09644790.js"><link rel="prefetch" href="/assets/js/397.76163964.js"><link rel="prefetch" href="/assets/js/398.377fd8fc.js"><link rel="prefetch" href="/assets/js/399.39059be5.js"><link rel="prefetch" href="/assets/js/40.a21abf05.js"><link rel="prefetch" href="/assets/js/400.559a547f.js"><link rel="prefetch" href="/assets/js/401.bc6d738c.js"><link rel="prefetch" href="/assets/js/402.c504ed7b.js"><link rel="prefetch" href="/assets/js/403.77a0af9c.js"><link rel="prefetch" href="/assets/js/404.0f408cc6.js"><link rel="prefetch" href="/assets/js/405.90b0bab6.js"><link rel="prefetch" href="/assets/js/406.01b11432.js"><link rel="prefetch" href="/assets/js/407.58991ce5.js"><link rel="prefetch" href="/assets/js/408.9806278e.js"><link rel="prefetch" href="/assets/js/409.8d9b4bb3.js"><link rel="prefetch" href="/assets/js/41.6bcfc592.js"><link rel="prefetch" href="/assets/js/410.02dee620.js"><link rel="prefetch" href="/assets/js/411.3d12d3a6.js"><link rel="prefetch" href="/assets/js/412.37a62624.js"><link rel="prefetch" href="/assets/js/413.bda7ca34.js"><link rel="prefetch" href="/assets/js/414.2abb6547.js"><link rel="prefetch" href="/assets/js/415.1d271923.js"><link rel="prefetch" href="/assets/js/416.d1b11dfe.js"><link rel="prefetch" href="/assets/js/417.fcbf07ff.js"><link rel="prefetch" href="/assets/js/418.524d40ba.js"><link rel="prefetch" href="/assets/js/419.f264e463.js"><link rel="prefetch" href="/assets/js/42.ec85a270.js"><link rel="prefetch" href="/assets/js/420.8b99e60d.js"><link rel="prefetch" href="/assets/js/421.c697d876.js"><link rel="prefetch" href="/assets/js/422.4af54ae0.js"><link rel="prefetch" href="/assets/js/423.b75f24ff.js"><link rel="prefetch" href="/assets/js/424.ea80054f.js"><link rel="prefetch" href="/assets/js/425.804b48b0.js"><link rel="prefetch" href="/assets/js/426.ffed8383.js"><link rel="prefetch" href="/assets/js/427.2040bd22.js"><link rel="prefetch" href="/assets/js/428.b878fb56.js"><link rel="prefetch" href="/assets/js/429.f81fd922.js"><link rel="prefetch" href="/assets/js/43.c174449d.js"><link rel="prefetch" href="/assets/js/430.16f328ab.js"><link rel="prefetch" href="/assets/js/431.56f11924.js"><link rel="prefetch" href="/assets/js/432.e4c77710.js"><link rel="prefetch" href="/assets/js/433.29acf14b.js"><link rel="prefetch" href="/assets/js/434.33ee22fc.js"><link rel="prefetch" href="/assets/js/435.516f7600.js"><link rel="prefetch" href="/assets/js/436.28ae526a.js"><link rel="prefetch" href="/assets/js/437.b9bac473.js"><link rel="prefetch" href="/assets/js/438.711bd934.js"><link rel="prefetch" href="/assets/js/439.fe5f28bd.js"><link rel="prefetch" href="/assets/js/44.8704338b.js"><link rel="prefetch" href="/assets/js/440.b2f48747.js"><link rel="prefetch" href="/assets/js/441.4862a724.js"><link rel="prefetch" href="/assets/js/442.751f8ae7.js"><link rel="prefetch" href="/assets/js/443.9998dbe9.js"><link rel="prefetch" href="/assets/js/444.23d3f688.js"><link rel="prefetch" href="/assets/js/445.72419f35.js"><link rel="prefetch" href="/assets/js/446.21e02b7b.js"><link rel="prefetch" href="/assets/js/447.6bd039e5.js"><link rel="prefetch" href="/assets/js/448.af29ff31.js"><link rel="prefetch" href="/assets/js/449.bbdca196.js"><link rel="prefetch" href="/assets/js/45.f8a2a3b3.js"><link rel="prefetch" href="/assets/js/450.32e470b8.js"><link rel="prefetch" href="/assets/js/451.f4c8ff6a.js"><link rel="prefetch" href="/assets/js/452.c0ec8943.js"><link rel="prefetch" href="/assets/js/453.5af475c6.js"><link rel="prefetch" href="/assets/js/454.567aa6c1.js"><link rel="prefetch" href="/assets/js/455.326072d1.js"><link rel="prefetch" href="/assets/js/456.64b88847.js"><link rel="prefetch" href="/assets/js/457.61c91559.js"><link rel="prefetch" href="/assets/js/458.4f4d43d6.js"><link rel="prefetch" href="/assets/js/459.a88891cb.js"><link rel="prefetch" href="/assets/js/46.90855a0f.js"><link rel="prefetch" href="/assets/js/460.fb9e15f6.js"><link rel="prefetch" href="/assets/js/461.998a4991.js"><link rel="prefetch" href="/assets/js/462.56ecfb03.js"><link rel="prefetch" href="/assets/js/463.582cd053.js"><link rel="prefetch" href="/assets/js/464.f12a0050.js"><link rel="prefetch" href="/assets/js/465.cc3b08a8.js"><link rel="prefetch" href="/assets/js/466.ea7e4ce2.js"><link rel="prefetch" href="/assets/js/467.58700d93.js"><link rel="prefetch" href="/assets/js/468.bb9998cd.js"><link rel="prefetch" href="/assets/js/469.232d261d.js"><link rel="prefetch" href="/assets/js/47.02516d33.js"><link rel="prefetch" href="/assets/js/470.90ab2be8.js"><link rel="prefetch" href="/assets/js/471.3652fec6.js"><link rel="prefetch" href="/assets/js/472.bc7517c9.js"><link rel="prefetch" href="/assets/js/473.27b7892f.js"><link rel="prefetch" href="/assets/js/474.0d488768.js"><link rel="prefetch" href="/assets/js/475.bc33cf17.js"><link rel="prefetch" href="/assets/js/476.76ce67eb.js"><link rel="prefetch" href="/assets/js/477.a20657f6.js"><link rel="prefetch" href="/assets/js/478.8905ef26.js"><link rel="prefetch" href="/assets/js/479.23ec3dc9.js"><link rel="prefetch" href="/assets/js/48.8d38983c.js"><link rel="prefetch" href="/assets/js/480.105bf58e.js"><link rel="prefetch" href="/assets/js/481.d62a3699.js"><link rel="prefetch" href="/assets/js/482.6cb10cdb.js"><link rel="prefetch" href="/assets/js/483.15b9ef53.js"><link rel="prefetch" href="/assets/js/484.794aff9c.js"><link rel="prefetch" href="/assets/js/485.3e6ef3cb.js"><link rel="prefetch" href="/assets/js/486.fc20eb22.js"><link rel="prefetch" href="/assets/js/487.2a4f7d47.js"><link rel="prefetch" href="/assets/js/488.24ba9af5.js"><link rel="prefetch" href="/assets/js/489.d451928e.js"><link rel="prefetch" href="/assets/js/49.bd70c59c.js"><link rel="prefetch" href="/assets/js/490.d83e4fc7.js"><link rel="prefetch" href="/assets/js/491.0210a738.js"><link rel="prefetch" href="/assets/js/492.3a69cd85.js"><link rel="prefetch" href="/assets/js/493.89d2920f.js"><link rel="prefetch" href="/assets/js/494.b7d1c15e.js"><link rel="prefetch" href="/assets/js/495.7ccfe17f.js"><link rel="prefetch" href="/assets/js/496.0d6c912a.js"><link rel="prefetch" href="/assets/js/497.087ca2c6.js"><link rel="prefetch" href="/assets/js/498.f2b3c894.js"><link rel="prefetch" href="/assets/js/499.e741f312.js"><link rel="prefetch" href="/assets/js/5.405f2620.js"><link rel="prefetch" href="/assets/js/50.9df07553.js"><link rel="prefetch" href="/assets/js/500.cb9babb9.js"><link rel="prefetch" href="/assets/js/501.63a859b6.js"><link rel="prefetch" href="/assets/js/502.f346b273.js"><link rel="prefetch" href="/assets/js/503.cdcd3de3.js"><link rel="prefetch" href="/assets/js/504.e83ec450.js"><link rel="prefetch" href="/assets/js/505.95f18293.js"><link rel="prefetch" href="/assets/js/506.02060a3c.js"><link rel="prefetch" href="/assets/js/507.859d6ae4.js"><link rel="prefetch" href="/assets/js/508.9724d886.js"><link rel="prefetch" href="/assets/js/509.e17dd53e.js"><link rel="prefetch" href="/assets/js/51.3dfc6350.js"><link rel="prefetch" href="/assets/js/510.ea0c942f.js"><link rel="prefetch" href="/assets/js/511.64a7f9a8.js"><link rel="prefetch" href="/assets/js/512.6cce418a.js"><link rel="prefetch" href="/assets/js/513.ea813fe8.js"><link rel="prefetch" href="/assets/js/514.10242470.js"><link rel="prefetch" href="/assets/js/515.5308bdf6.js"><link rel="prefetch" href="/assets/js/516.dfb113bc.js"><link rel="prefetch" href="/assets/js/517.96c71069.js"><link rel="prefetch" href="/assets/js/518.5594480e.js"><link rel="prefetch" href="/assets/js/519.91e848ae.js"><link rel="prefetch" href="/assets/js/52.dd230cd7.js"><link rel="prefetch" href="/assets/js/520.ebe69ce9.js"><link rel="prefetch" href="/assets/js/521.92b80342.js"><link rel="prefetch" href="/assets/js/522.6ce581ea.js"><link rel="prefetch" href="/assets/js/523.40b7f2f9.js"><link rel="prefetch" href="/assets/js/524.4ef256d3.js"><link rel="prefetch" href="/assets/js/525.19741e4a.js"><link rel="prefetch" href="/assets/js/526.e5de1675.js"><link rel="prefetch" href="/assets/js/527.9a79cd42.js"><link rel="prefetch" href="/assets/js/528.72732eb8.js"><link rel="prefetch" href="/assets/js/529.2ea03e45.js"><link rel="prefetch" href="/assets/js/53.a349c565.js"><link rel="prefetch" href="/assets/js/530.5d1103e7.js"><link rel="prefetch" href="/assets/js/531.82b032d6.js"><link rel="prefetch" href="/assets/js/532.12ee4beb.js"><link rel="prefetch" href="/assets/js/533.db9a90f7.js"><link rel="prefetch" href="/assets/js/534.fe139db4.js"><link rel="prefetch" href="/assets/js/535.056a6fbb.js"><link rel="prefetch" href="/assets/js/536.6bf85c15.js"><link rel="prefetch" href="/assets/js/537.6e2e1ccf.js"><link rel="prefetch" href="/assets/js/538.54eddb3b.js"><link rel="prefetch" href="/assets/js/539.6f00a207.js"><link rel="prefetch" href="/assets/js/54.e292b52f.js"><link rel="prefetch" href="/assets/js/540.9c956205.js"><link rel="prefetch" href="/assets/js/541.50f41228.js"><link rel="prefetch" href="/assets/js/542.a2b1879e.js"><link rel="prefetch" href="/assets/js/543.4e5e17c9.js"><link rel="prefetch" href="/assets/js/544.63d85227.js"><link rel="prefetch" href="/assets/js/545.c3923644.js"><link rel="prefetch" href="/assets/js/546.e64ad073.js"><link rel="prefetch" href="/assets/js/547.35a8752d.js"><link rel="prefetch" href="/assets/js/548.b62a1348.js"><link rel="prefetch" href="/assets/js/549.369e2ea0.js"><link rel="prefetch" href="/assets/js/55.21bb2983.js"><link rel="prefetch" href="/assets/js/550.b4632248.js"><link rel="prefetch" href="/assets/js/551.18f1879c.js"><link rel="prefetch" href="/assets/js/552.162e63cd.js"><link rel="prefetch" href="/assets/js/553.6998130e.js"><link rel="prefetch" href="/assets/js/554.89126c3d.js"><link rel="prefetch" href="/assets/js/555.a5f63b8a.js"><link rel="prefetch" href="/assets/js/556.35381cef.js"><link rel="prefetch" href="/assets/js/557.ceeecf52.js"><link rel="prefetch" href="/assets/js/558.253e6e4f.js"><link rel="prefetch" href="/assets/js/559.5cfbb773.js"><link rel="prefetch" href="/assets/js/56.5382d6b4.js"><link rel="prefetch" href="/assets/js/560.cca52f22.js"><link rel="prefetch" href="/assets/js/561.ea8d1141.js"><link rel="prefetch" href="/assets/js/562.c32e7b96.js"><link rel="prefetch" href="/assets/js/563.9bdd42e7.js"><link rel="prefetch" href="/assets/js/564.b3b87ec0.js"><link rel="prefetch" href="/assets/js/565.4be0d0f7.js"><link rel="prefetch" href="/assets/js/566.9f379d12.js"><link rel="prefetch" href="/assets/js/567.261e3181.js"><link rel="prefetch" href="/assets/js/568.4229e365.js"><link rel="prefetch" href="/assets/js/569.e662c167.js"><link rel="prefetch" href="/assets/js/57.8129f7e0.js"><link rel="prefetch" href="/assets/js/570.97ff6423.js"><link rel="prefetch" href="/assets/js/571.de1377cd.js"><link rel="prefetch" href="/assets/js/572.48b8400b.js"><link rel="prefetch" href="/assets/js/573.8251ebaf.js"><link rel="prefetch" href="/assets/js/574.ec3d6c1e.js"><link rel="prefetch" href="/assets/js/575.b0d429a1.js"><link rel="prefetch" href="/assets/js/576.98ce9170.js"><link rel="prefetch" href="/assets/js/577.85fc2017.js"><link rel="prefetch" href="/assets/js/578.1393ac7f.js"><link rel="prefetch" href="/assets/js/579.1340e178.js"><link rel="prefetch" href="/assets/js/58.85ac2740.js"><link rel="prefetch" href="/assets/js/580.a5979445.js"><link rel="prefetch" href="/assets/js/581.effdc269.js"><link rel="prefetch" href="/assets/js/582.13276063.js"><link rel="prefetch" href="/assets/js/583.357a2443.js"><link rel="prefetch" href="/assets/js/584.338ef731.js"><link rel="prefetch" href="/assets/js/585.87932741.js"><link rel="prefetch" href="/assets/js/586.b1d6e000.js"><link rel="prefetch" href="/assets/js/587.ed5b8377.js"><link rel="prefetch" href="/assets/js/588.16d2c418.js"><link rel="prefetch" href="/assets/js/589.c96fd7fa.js"><link rel="prefetch" href="/assets/js/59.0b225757.js"><link rel="prefetch" href="/assets/js/590.1a06b2a0.js"><link rel="prefetch" href="/assets/js/591.0efd886c.js"><link rel="prefetch" href="/assets/js/592.b22d0ef5.js"><link rel="prefetch" href="/assets/js/593.84ed6ebe.js"><link rel="prefetch" href="/assets/js/594.cd721b88.js"><link rel="prefetch" href="/assets/js/595.2400817a.js"><link rel="prefetch" href="/assets/js/596.f2c512d1.js"><link rel="prefetch" href="/assets/js/597.df10ec57.js"><link rel="prefetch" href="/assets/js/598.61ef6a7d.js"><link rel="prefetch" href="/assets/js/599.0bebb562.js"><link rel="prefetch" href="/assets/js/60.3bbab51d.js"><link rel="prefetch" href="/assets/js/600.1ea7596f.js"><link rel="prefetch" href="/assets/js/601.f2642bb3.js"><link rel="prefetch" href="/assets/js/602.400cc987.js"><link rel="prefetch" href="/assets/js/603.db77d173.js"><link rel="prefetch" href="/assets/js/604.0ffa30ae.js"><link rel="prefetch" href="/assets/js/605.32ca9607.js"><link rel="prefetch" href="/assets/js/606.8c1e5683.js"><link rel="prefetch" href="/assets/js/607.9c9463ef.js"><link rel="prefetch" href="/assets/js/608.d5efa77e.js"><link rel="prefetch" href="/assets/js/609.5bbffb7d.js"><link rel="prefetch" href="/assets/js/61.f7301486.js"><link rel="prefetch" href="/assets/js/610.5b0fc9da.js"><link rel="prefetch" href="/assets/js/611.bb8058c9.js"><link rel="prefetch" href="/assets/js/612.b0788f43.js"><link rel="prefetch" href="/assets/js/613.49511e65.js"><link rel="prefetch" href="/assets/js/614.fae3eacf.js"><link rel="prefetch" href="/assets/js/615.359e5899.js"><link rel="prefetch" href="/assets/js/616.905132f4.js"><link rel="prefetch" href="/assets/js/617.6c8c594e.js"><link rel="prefetch" href="/assets/js/618.6ac4f3ff.js"><link rel="prefetch" href="/assets/js/619.411a0c14.js"><link rel="prefetch" href="/assets/js/62.9aeede84.js"><link rel="prefetch" href="/assets/js/620.56155724.js"><link rel="prefetch" href="/assets/js/621.149d7933.js"><link rel="prefetch" href="/assets/js/622.f0c9bc08.js"><link rel="prefetch" href="/assets/js/623.e0989fbe.js"><link rel="prefetch" href="/assets/js/624.80b1f6a9.js"><link rel="prefetch" href="/assets/js/625.a0a392c4.js"><link rel="prefetch" href="/assets/js/626.56fd4e8a.js"><link rel="prefetch" href="/assets/js/627.264e7313.js"><link rel="prefetch" href="/assets/js/628.7a868b19.js"><link rel="prefetch" href="/assets/js/629.e7e15da1.js"><link rel="prefetch" href="/assets/js/63.4df55c8b.js"><link rel="prefetch" href="/assets/js/630.998c9b61.js"><link rel="prefetch" href="/assets/js/631.69aa049c.js"><link rel="prefetch" href="/assets/js/632.da3882c1.js"><link rel="prefetch" href="/assets/js/633.0d49adf0.js"><link rel="prefetch" href="/assets/js/634.f9984ede.js"><link rel="prefetch" href="/assets/js/635.f0439f65.js"><link rel="prefetch" href="/assets/js/636.54de4194.js"><link rel="prefetch" href="/assets/js/637.55d1c226.js"><link rel="prefetch" href="/assets/js/638.2a9a510f.js"><link rel="prefetch" href="/assets/js/639.8bec360e.js"><link rel="prefetch" href="/assets/js/64.7f3e5e81.js"><link rel="prefetch" href="/assets/js/640.30d7f96e.js"><link rel="prefetch" href="/assets/js/641.68100098.js"><link rel="prefetch" href="/assets/js/642.4b793817.js"><link rel="prefetch" href="/assets/js/643.d86a81ea.js"><link rel="prefetch" href="/assets/js/644.76327ea2.js"><link rel="prefetch" href="/assets/js/645.0ac6a923.js"><link rel="prefetch" href="/assets/js/646.cd92f728.js"><link rel="prefetch" href="/assets/js/647.f2c624e1.js"><link rel="prefetch" href="/assets/js/648.c8f3b955.js"><link rel="prefetch" href="/assets/js/649.6370753b.js"><link rel="prefetch" href="/assets/js/65.2beeae9b.js"><link rel="prefetch" href="/assets/js/650.afe31909.js"><link rel="prefetch" href="/assets/js/651.87971ec0.js"><link rel="prefetch" href="/assets/js/652.0adf10a6.js"><link rel="prefetch" href="/assets/js/653.1f655726.js"><link rel="prefetch" href="/assets/js/654.53e24c7c.js"><link rel="prefetch" href="/assets/js/655.c95a66ea.js"><link rel="prefetch" href="/assets/js/656.38b5a5ea.js"><link rel="prefetch" href="/assets/js/657.3167aa94.js"><link rel="prefetch" href="/assets/js/658.7c40ff62.js"><link rel="prefetch" href="/assets/js/659.5d2b9b54.js"><link rel="prefetch" href="/assets/js/66.44b214db.js"><link rel="prefetch" href="/assets/js/660.96a8da9e.js"><link rel="prefetch" href="/assets/js/661.4de3b6c1.js"><link rel="prefetch" href="/assets/js/662.7d9bf181.js"><link rel="prefetch" href="/assets/js/663.4ccaf40a.js"><link rel="prefetch" href="/assets/js/664.7ab4fa53.js"><link rel="prefetch" href="/assets/js/665.32245d26.js"><link rel="prefetch" href="/assets/js/666.e6617151.js"><link rel="prefetch" href="/assets/js/667.fb3b0547.js"><link rel="prefetch" href="/assets/js/668.3d1b2e36.js"><link rel="prefetch" href="/assets/js/669.b769905f.js"><link rel="prefetch" href="/assets/js/67.c31aaacf.js"><link rel="prefetch" href="/assets/js/670.88ed3af3.js"><link rel="prefetch" href="/assets/js/671.1aff6bfe.js"><link rel="prefetch" href="/assets/js/672.c90888f7.js"><link rel="prefetch" href="/assets/js/673.81241fdc.js"><link rel="prefetch" href="/assets/js/674.838a424d.js"><link rel="prefetch" href="/assets/js/675.603ac896.js"><link rel="prefetch" href="/assets/js/676.ff44b5dc.js"><link rel="prefetch" href="/assets/js/677.41a8087a.js"><link rel="prefetch" href="/assets/js/678.f0eb8d04.js"><link rel="prefetch" href="/assets/js/679.db78199e.js"><link rel="prefetch" href="/assets/js/68.08607c89.js"><link rel="prefetch" href="/assets/js/680.8fded9d4.js"><link rel="prefetch" href="/assets/js/681.0b019dfd.js"><link rel="prefetch" href="/assets/js/682.746e9190.js"><link rel="prefetch" href="/assets/js/683.d5c00845.js"><link rel="prefetch" href="/assets/js/684.b3207cad.js"><link rel="prefetch" href="/assets/js/685.d78f18ba.js"><link rel="prefetch" href="/assets/js/686.5aaecd19.js"><link rel="prefetch" href="/assets/js/687.821a06f4.js"><link rel="prefetch" href="/assets/js/688.8bbc1890.js"><link rel="prefetch" href="/assets/js/689.79b49e8c.js"><link rel="prefetch" href="/assets/js/69.509245d6.js"><link rel="prefetch" href="/assets/js/690.fa62f9dd.js"><link rel="prefetch" href="/assets/js/691.d3eb1a60.js"><link rel="prefetch" href="/assets/js/692.738f14bb.js"><link rel="prefetch" href="/assets/js/693.e6a497a2.js"><link rel="prefetch" href="/assets/js/694.6eea1c54.js"><link rel="prefetch" href="/assets/js/695.88e6acee.js"><link rel="prefetch" href="/assets/js/696.de10297f.js"><link rel="prefetch" href="/assets/js/697.96d04062.js"><link rel="prefetch" href="/assets/js/698.200cc84f.js"><link rel="prefetch" href="/assets/js/699.f11fc627.js"><link rel="prefetch" href="/assets/js/7.c16198b8.js"><link rel="prefetch" href="/assets/js/70.5f6285b1.js"><link rel="prefetch" href="/assets/js/700.93d48f59.js"><link rel="prefetch" href="/assets/js/701.b861f29a.js"><link rel="prefetch" href="/assets/js/702.dc82e05c.js"><link rel="prefetch" href="/assets/js/703.625ce87c.js"><link rel="prefetch" href="/assets/js/704.005a0a7c.js"><link rel="prefetch" href="/assets/js/705.16ad9230.js"><link rel="prefetch" href="/assets/js/706.4eead30a.js"><link rel="prefetch" href="/assets/js/707.730306ce.js"><link rel="prefetch" href="/assets/js/708.e37e743a.js"><link rel="prefetch" href="/assets/js/709.f2144f52.js"><link rel="prefetch" href="/assets/js/71.d5d0dae5.js"><link rel="prefetch" href="/assets/js/710.ee9d9b17.js"><link rel="prefetch" href="/assets/js/711.2813c338.js"><link rel="prefetch" href="/assets/js/712.e801bce4.js"><link rel="prefetch" href="/assets/js/713.21fc267c.js"><link rel="prefetch" href="/assets/js/714.4ec35525.js"><link rel="prefetch" href="/assets/js/715.fdc3cc84.js"><link rel="prefetch" href="/assets/js/716.324932ad.js"><link rel="prefetch" href="/assets/js/717.a072a66f.js"><link rel="prefetch" href="/assets/js/718.575e0305.js"><link rel="prefetch" href="/assets/js/719.5fdd55de.js"><link rel="prefetch" href="/assets/js/72.25648231.js"><link rel="prefetch" href="/assets/js/720.61477f23.js"><link rel="prefetch" href="/assets/js/721.c8bdab00.js"><link rel="prefetch" href="/assets/js/722.9255f385.js"><link rel="prefetch" href="/assets/js/723.f27792a4.js"><link rel="prefetch" href="/assets/js/724.cd504f88.js"><link rel="prefetch" href="/assets/js/725.55c845fa.js"><link rel="prefetch" href="/assets/js/726.bb49a9db.js"><link rel="prefetch" href="/assets/js/727.53d587fe.js"><link rel="prefetch" href="/assets/js/728.86972387.js"><link rel="prefetch" href="/assets/js/729.02fa0263.js"><link rel="prefetch" href="/assets/js/73.29902c1f.js"><link rel="prefetch" href="/assets/js/730.817156d1.js"><link rel="prefetch" href="/assets/js/731.6f5d6735.js"><link rel="prefetch" href="/assets/js/732.9a5ff781.js"><link rel="prefetch" href="/assets/js/733.bcb13916.js"><link rel="prefetch" href="/assets/js/734.11482b19.js"><link rel="prefetch" href="/assets/js/735.8c0d62f3.js"><link rel="prefetch" href="/assets/js/736.06465705.js"><link rel="prefetch" href="/assets/js/737.79741d87.js"><link rel="prefetch" href="/assets/js/738.cad12ff9.js"><link rel="prefetch" href="/assets/js/739.cb09e552.js"><link rel="prefetch" href="/assets/js/74.bcf666a0.js"><link rel="prefetch" href="/assets/js/740.029b1950.js"><link rel="prefetch" href="/assets/js/741.b937216a.js"><link rel="prefetch" href="/assets/js/742.ec02c706.js"><link rel="prefetch" href="/assets/js/743.70a96283.js"><link rel="prefetch" href="/assets/js/744.909b870c.js"><link rel="prefetch" href="/assets/js/745.80defb2d.js"><link rel="prefetch" href="/assets/js/746.fb972248.js"><link rel="prefetch" href="/assets/js/747.1a7b52fd.js"><link rel="prefetch" href="/assets/js/748.036f5d16.js"><link rel="prefetch" href="/assets/js/749.bd9a413d.js"><link rel="prefetch" href="/assets/js/75.23c5a54d.js"><link rel="prefetch" href="/assets/js/750.3f1ae8f5.js"><link rel="prefetch" href="/assets/js/751.8897bc9f.js"><link rel="prefetch" href="/assets/js/752.9b387659.js"><link rel="prefetch" href="/assets/js/753.f411ce21.js"><link rel="prefetch" href="/assets/js/754.26def684.js"><link rel="prefetch" href="/assets/js/755.923aff62.js"><link rel="prefetch" href="/assets/js/756.9965743a.js"><link rel="prefetch" href="/assets/js/757.0c6bbbfd.js"><link rel="prefetch" href="/assets/js/758.a830f8b1.js"><link rel="prefetch" href="/assets/js/759.987cad77.js"><link rel="prefetch" href="/assets/js/76.f54f3d4f.js"><link rel="prefetch" href="/assets/js/760.9f2652a0.js"><link rel="prefetch" href="/assets/js/761.df01a0ee.js"><link rel="prefetch" href="/assets/js/762.e0c05a1a.js"><link rel="prefetch" href="/assets/js/763.da8a60bd.js"><link rel="prefetch" href="/assets/js/764.9f2a2830.js"><link rel="prefetch" href="/assets/js/765.44e61161.js"><link rel="prefetch" href="/assets/js/766.cd7da8c1.js"><link rel="prefetch" href="/assets/js/767.6ea1fea2.js"><link rel="prefetch" href="/assets/js/768.91529b8f.js"><link rel="prefetch" href="/assets/js/769.194d7a3e.js"><link rel="prefetch" href="/assets/js/77.3d43a163.js"><link rel="prefetch" href="/assets/js/770.227fd5b9.js"><link rel="prefetch" href="/assets/js/771.44d5e37e.js"><link rel="prefetch" href="/assets/js/772.234d9bf6.js"><link rel="prefetch" href="/assets/js/773.ff1dfb6a.js"><link rel="prefetch" href="/assets/js/774.d401364f.js"><link rel="prefetch" href="/assets/js/775.37a7cf41.js"><link rel="prefetch" href="/assets/js/776.0cd10853.js"><link rel="prefetch" href="/assets/js/777.599a3a48.js"><link rel="prefetch" href="/assets/js/778.eef27a95.js"><link rel="prefetch" href="/assets/js/779.29351199.js"><link rel="prefetch" href="/assets/js/78.fd0780ac.js"><link rel="prefetch" href="/assets/js/780.74caed94.js"><link rel="prefetch" href="/assets/js/781.ee0fa9b5.js"><link rel="prefetch" href="/assets/js/782.7cffed09.js"><link rel="prefetch" href="/assets/js/783.7f01f518.js"><link rel="prefetch" href="/assets/js/784.5f65e3d7.js"><link rel="prefetch" href="/assets/js/785.d7e13880.js"><link rel="prefetch" href="/assets/js/786.6110d12f.js"><link rel="prefetch" href="/assets/js/787.334a5cdd.js"><link rel="prefetch" href="/assets/js/788.f261bc71.js"><link rel="prefetch" href="/assets/js/789.b6d74f7d.js"><link rel="prefetch" href="/assets/js/79.7b5d6224.js"><link rel="prefetch" href="/assets/js/790.fa948ec4.js"><link rel="prefetch" href="/assets/js/791.22080013.js"><link rel="prefetch" href="/assets/js/792.31ce806c.js"><link rel="prefetch" href="/assets/js/793.9fd0c56f.js"><link rel="prefetch" href="/assets/js/794.44a8cd9c.js"><link rel="prefetch" href="/assets/js/795.9f8346e5.js"><link rel="prefetch" href="/assets/js/796.0de9c7a1.js"><link rel="prefetch" href="/assets/js/797.83ac32a6.js"><link rel="prefetch" href="/assets/js/798.393fc81d.js"><link rel="prefetch" href="/assets/js/799.c1fb3981.js"><link rel="prefetch" href="/assets/js/8.3275ed06.js"><link rel="prefetch" href="/assets/js/80.df3f0a1f.js"><link rel="prefetch" href="/assets/js/800.2832adeb.js"><link rel="prefetch" href="/assets/js/801.04c58fc4.js"><link rel="prefetch" href="/assets/js/81.3d90ef6b.js"><link rel="prefetch" href="/assets/js/82.2d42448d.js"><link rel="prefetch" href="/assets/js/83.900b4de2.js"><link rel="prefetch" href="/assets/js/84.ff570f67.js"><link rel="prefetch" href="/assets/js/85.e3b3af39.js"><link rel="prefetch" href="/assets/js/86.17b5aedc.js"><link rel="prefetch" href="/assets/js/87.f931d1d6.js"><link rel="prefetch" href="/assets/js/88.d55863cd.js"><link rel="prefetch" href="/assets/js/89.15a9a6d7.js"><link rel="prefetch" href="/assets/js/9.04948a9d.js"><link rel="prefetch" href="/assets/js/90.22696aa9.js"><link rel="prefetch" href="/assets/js/91.f1bd8a2e.js"><link rel="prefetch" href="/assets/js/92.85733094.js"><link rel="prefetch" href="/assets/js/93.59bacfd7.js"><link rel="prefetch" href="/assets/js/94.a5f9b7a0.js"><link rel="prefetch" href="/assets/js/95.be52d65a.js"><link rel="prefetch" href="/assets/js/96.0b76ba8e.js"><link rel="prefetch" href="/assets/js/97.28183cd4.js"><link rel="prefetch" href="/assets/js/98.2d22829c.js"><link rel="prefetch" href="/assets/js/99.ed602a20.js">
    <link rel="stylesheet" href="/assets/css/0.styles.a3df589e.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">AJ</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link">主页</a></div><div class="nav-item"><a href="/op/" class="nav-link">Devops</a></div><div class="nav-item"><a href="/golang/" class="nav-link">Go</a></div><div class="nav-item"><a href="/go-block/" class="nav-link">区块链</a></div><div class="nav-item"><a href="/k8s/" class="nav-link">k8s</a></div><div class="nav-item"><a href="/about.html" class="nav-link">关于我</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="更多" class="dropdown-title"><span class="title">更多</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/go-learning/" class="nav-link">go-learning</a></li><li class="dropdown-item"><!----> <a href="/post/flutter-guide/" class="nav-link">flutter</a></li><li class="dropdown-item"><!----> <a href="/mysql/" class="nav-link">mysql</a></li><li class="dropdown-item"><!----> <a href="/python/" class="nav-link">python</a></li></ul></div></div> <a href="https://github.com/ChinaArJun" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link">主页</a></div><div class="nav-item"><a href="/op/" class="nav-link">Devops</a></div><div class="nav-item"><a href="/golang/" class="nav-link">Go</a></div><div class="nav-item"><a href="/go-block/" class="nav-link">区块链</a></div><div class="nav-item"><a href="/k8s/" class="nav-link">k8s</a></div><div class="nav-item"><a href="/about.html" class="nav-link">关于我</a></div><div class="nav-item"><div class="dropdown-wrapper"><button type="button" aria-label="更多" class="dropdown-title"><span class="title">更多</span> <span class="arrow right"></span></button> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/go-learning/" class="nav-link">go-learning</a></li><li class="dropdown-item"><!----> <a href="/post/flutter-guide/" class="nav-link">flutter</a></li><li class="dropdown-item"><!----> <a href="/mysql/" class="nav-link">mysql</a></li><li class="dropdown-item"><!----> <a href="/python/" class="nav-link">python</a></li></ul></div></div> <a href="https://github.com/ChinaArJun" target="_blank" rel="noopener noreferrer" class="repo-link">
    GitHub
    <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></nav> <div></div> <div style="padding-left:1.5rem;"><div></div></div> <!----> </aside> <!----> <!----> <main class="page"><div class="theme-default-content" style="margin-bottom:-5rem;"><div class="bar"><div class="bar-intro"><div class="text">
      流逝的是岁月，不变的是情怀.
        </div> <div class="text">
      坚持学习，是为了成就更好的自己. <br></div> <div>公众号[中关村程序员]</div></div></div> <!----></div> <div class="theme-default-content content__default"><p><a href="https://github.com/golang/go/blob/master/src/runtime/mgc.go" target="_blank" rel="noopener noreferrer">GC官方源码<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></p> <blockquote><p>本文写于 Go 1.14 beta1，当文中提及目前、目前版本等字眼时均指 Go 1.14，此外，文中所有 go 命令版本均为 Go 1.14。</p></blockquote> <h1 id="gc-的认识"><a href="#gc-的认识" class="header-anchor">#</a> GC 的认识</h1> <h2 id="_1-什么是-gc，有什么作用？"><a href="#_1-什么是-gc，有什么作用？" class="header-anchor">#</a> 1. 什么是 GC，有什么作用？</h2> <p><code>GC</code>，全称 <code>Garbage Collection</code>，即垃圾回收，是一种自动内存管理的机制。</p> <p>当程序向操作系统申请的内存不再需要时，垃圾回收主动将其回收并供其他代码进行内存申请时候复用，或者将其归还给操作系统，这种针对内存级别资源的自动回收过程，即为垃圾回收。而负责垃圾回收的程序组件，即为垃圾回收器。</p> <p>垃圾回收其实一个完美的 “Simplicity is Complicated” 的例子。一方面，程序员受益于 GC，无需操心、也不再需要对内存进行手动的申请和释放操作，GC 在程序运行时自动释放残留的内存。另一方面，GC 对程序员几乎不可见，仅在程序需要进行特殊优化时，通过提供可调控的 API，对 GC 的运行时机、运行开销进行把控的时候才得以现身。</p> <p>通常，垃圾回收器的执行过程被划分为两个半独立的组件：</p> <ul><li>赋值器（Mutator）：这一名称本质上是在指代用户态的代码。因为对垃圾回收器而言，用户态的代码仅仅只是在修改对象之间的引用关系，也就是在对象图（对象之间引用关系的一个有向图）上进行操作。</li> <li>回收器（Collector）：负责执行垃圾回收的代码。</li></ul> <h2 id="_2-根对象到底是什么？"><a href="#_2-根对象到底是什么？" class="header-anchor">#</a> 2. 根对象到底是什么？</h2> <p>根对象在垃圾回收的术语中又叫做根集合，它是垃圾回收器在标记过程时最先检查的对象，包括：</p> <ol><li>全局变量：程序在编译期就能确定的那些存在于程序整个生命周期的变量。</li> <li>执行栈：每个 goroutine 都包含自己的执行栈，这些执行栈上包含栈上的变量及指向分配的堆内存区块的指针。</li> <li>寄存器：寄存器的值可能表示一个指针，参与计算的这些指针可能指向某些赋值器分配的堆内存区块。</li></ol> <h2 id="_3-常见的-gc-实现方式有哪些？go-语言的-gc-使用的是什么？"><a href="#_3-常见的-gc-实现方式有哪些？go-语言的-gc-使用的是什么？" class="header-anchor">#</a> 3. 常见的 GC 实现方式有哪些？Go 语言的 GC 使用的是什么？</h2> <p>所有的 GC 算法其存在形式可以归结为追踪（Tracing）和引用计数（Reference Counting）这两种形式的混合运用。</p> <ul><li><p>追踪式 GC</p> <p>从根对象出发，根据对象之间的引用信息，一步步推进直到扫描完毕整个堆并确定需要保留的对象，从而回收所有可回收的对象。Go、 Java、V8 对 JavaScript 的实现等均为追踪式 GC。</p></li> <li><p>引用计数式 GC</p> <p>每个对象自身包含一个被引用的计数器，当计数器归零时自动得到回收。因为此方法缺陷较多，在追求高性能时通常不被应用。Python、Objective-C 等均为引用计数式 GC。</p></li></ul> <p>目前比较常见的 GC 实现方式包括：</p> <ul><li>追踪式，分为多种不同类型，例如：
<ul><li>标记清扫：从根对象出发，将确定存活的对象进行标记，并清扫可以回收的对象。</li> <li>标记整理：为了解决内存碎片问题而提出，在标记过程中，将对象尽可能整理到一块连续的内存上。</li> <li>增量式：将标记与清扫的过程分批执行，每次执行很小的部分，从而增量的推进垃圾回收，达到近似实时、几乎无停顿的目的。</li> <li>增量整理：在增量式的基础上，增加对对象的整理过程。</li> <li>分代式：将对象根据存活时间的长短进行分类，存活时间小于某个值的为年轻代，存活时间大于某个值的为老年代，永远不会参与回收的对象为永久代。并根据分代假设（如果一个对象存活时间不长则倾向于被回收，如果一个对象已经存活很长时间则倾向于存活更长时间）对对象进行回收。</li></ul></li> <li>引用计数：根据对象自身的引用计数来回收，当引用计数归零时立即回收。</li></ul> <p>关于各类方法的详细介绍及其实现不在本文中详细讨论。对于 Go 而言，Go 的 GC 目前使用的是无分代（对象没有代际之分）、不整理（回收过程中不对对象进行移动与整理）、并发（与用户代码并发执行）的三色标记清扫算法。<a href="https://groups.google.com/d/msg/golang-nuts/KJiyv2mV2pU/wdBUH1mHCAAJ" target="_blank" rel="noopener noreferrer">原因<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>在于：</p> <ol><li>对象整理的优势是解决内存碎片问题以及“允许”使用顺序内存分配器。但 Go 运行时的分配算法基于 tcmalloc，基本上没有碎片问题。 并且顺序内存分配器在多线程的场景下并不适用。Go 使用的是基于 tcmalloc 的现代内存分配算法，对对象进行整理不会带来实质性的性能提升。</li> <li>分代 GC 依赖分代假设，即 GC 将主要的回收目标放在新创建的对象上（存活时间短，更倾向于被回收），而非频繁检查所有对象。但 Go 的编译器会通过<strong>逃逸分析</strong>将大部分新生对象存储在栈上（栈直接被回收），只有那些需要长期存在的对象才会被分配到需要进行垃圾回收的堆中。也就是说，分代 GC 回收的那些存活时间短的对象在 Go 中是直接被分配到栈上，当 goroutine 死亡后栈也会被直接回收，不需要 GC 的参与，进而分代假设并没有带来直接优势。并且 Go 的垃圾回收器与用户代码并发执行，使得 STW 的时间与对象的代际、对象的 size 没有关系。Go 团队更关注于如何更好地让 GC 与用户代码并发执行（使用适当的 CPU 来执行垃圾回收），而非减少停顿时间这一单一目标上。</li></ol> <h2 id="_4-三色标记法是什么？"><a href="#_4-三色标记法是什么？" class="header-anchor">#</a> 4. 三色标记法是什么？</h2> <p>理解<strong>三色标记法</strong>的关键是理解对象的<strong>三色抽象</strong>以及<strong>波面（wavefront）推进</strong>这两个概念。三色抽象只是一种描述追踪式回收器的方法，在实践中并没有实际含义，它的重要作用在于从逻辑上严密推导标记清理这种垃圾回收方法的正确性。也就是说，当我们谈及三色标记法时，通常指标记清扫的垃圾回收。</p> <p>从垃圾回收器的视角来看，三色抽象规定了三种不同类型的对象，并用不同的颜色相称：</p> <ul><li>白色对象（可能死亡）：未被回收器访问到的对象。在回收开始阶段，所有对象均为白色，当回收结束后，白色对象均不可达。</li> <li>灰色对象（波面）：已被回收器访问到的对象，但回收器需要对其中的一个或多个指针进行扫描，因为他们可能还指向白色对象。</li> <li>黑色对象（确定存活）：已被回收器访问到的对象，其中所有字段都已被扫描，黑色对象中任何一个指针都不可能直接指向白色对象。</li></ul> <p>这样三种不变性所定义的回收过程其实是一个<strong>波面</strong>不断前进的过程，这个波面同时也是黑色对象和白色对象的边界，灰色对象就是这个波面。</p> <p>当垃圾回收开始时，只有白色对象。随着标记过程开始进行时，灰色对象开始出现（着色），这时候波面便开始扩大。当一个对象的所有子节点均完成扫描时，会被着色为黑色。当整个堆遍历完成时，只剩下黑色和白色对象，这时的黑色对象为可达对象，即存活；而白色对象为不可达对象，即死亡。这个过程可以视为以灰色对象为波面，将黑色对象和白色对象分离，使波面不断向前推进，直到所有可达的灰色对象都变为黑色对象为止的过程。如下图所示：</p> <p><img src="https://user-images.githubusercontent.com/7698088/70995777-505fc800-210c-11ea-9f6d-3549f884ff46.png" alt="三色标记法全貌"></p> <p>图中展示了根对象、可达对象、不可达对象，黑、灰、白对象以及波面之间的关系。</p> <h2 id="_5-stw-是什么意思？"><a href="#_5-stw-是什么意思？" class="header-anchor">#</a> 5. STW 是什么意思？</h2> <p><code>STW</code> 是 <code>Stop the World</code> 的缩写，即万物静止，是指在垃圾回收过程中为了保证实现的正确性、防止无止境的内存增长等问题而不可避免的需要停止赋值器进一步操作对象图的一段过程。</p> <p>在这个过程中整个用户代码被停止或者放缓执行， <code>STW</code> 越长，对用户代码造成的影响（例如延迟）就越大，早期 Go 对垃圾回收器的实现中 <code>STW</code> 长达几百毫秒，对时间敏感的实时通信等应用程序会造成巨大的影响。我们来看一个例子：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;runtime&quot;</span>
	<span class="token string">&quot;time&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">for</span> <span class="token punctuation">{</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Millisecond<span class="token punctuation">)</span>
	runtime<span class="token punctuation">.</span><span class="token function">GC</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;OK&quot;</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>上面的这个程序在 Go 1.14 以前永远都不会输出 <code>OK</code>，其罪魁祸首是 STW 无限制的被延长。</p> <p>尽管 STW 如今已经优化到了半毫秒级别以下，但这个程序被卡死原因在于仍然是 STW 导致的。原因在于，GC 在进入 STW 时，需要等待让所有的用户态代码停止，但是 <code>for {}</code> 所在的 goroutine 永远都不会被中断，从而停留在 STW 阶段。实际实践中也是如此，当程序的某个 goroutine 长时间得不到停止，强行拖慢 STW，这种情况下造成的影响（卡死）是非常可怕的。好在自 Go 1.14 之后，这类 goroutine 能够被异步地抢占，从而使得 STW 的时间如同普通程序那样，不会超过半个毫秒，程序也不会因为仅仅等待一个 goroutine 的停止而停顿在 STW 阶段。</p> <h2 id="_6-如何观察-go-gc？"><a href="#_6-如何观察-go-gc？" class="header-anchor">#</a> 6. 如何观察 Go GC？</h2> <p>我们以下面的程序为例，先使用四种不同的方式来介绍如何观察 GC，并在后面的问题中通过几个详细的例子再来讨论如何优化 GC。</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">func</span> <span class="token function">allocate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token boolean">_</span> <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token operator">&lt;&lt;</span><span class="token number">20</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">1</span><span class="token punctuation">;</span> n <span class="token operator">&lt;</span> <span class="token number">100000</span><span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token function">allocate</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><h3 id="方式1：godebug-gctrace-1"><a href="#方式1：godebug-gctrace-1" class="header-anchor">#</a> 方式1：<code>GODEBUG=gctrace=1</code></h3> <p>我们首先可以通过</p> <div class="language- extra-class"><pre class="language-text"><code>$ go build -o main
$ GODEBUG=gctrace=1 ./main

gc 1 @0.000s 2%: 0.009+0.23+0.004 ms clock, 0.11+0.083/0.019/0.14+0.049 ms cpu, 4-&gt;6-&gt;2 MB, 5 MB goal, 12 P
scvg: 8 KB released
scvg: inuse: 3, idle: 60, sys: 63, released: 57, consumed: 6 (MB)
gc 2 @0.001s 2%: 0.018+1.1+0.029 ms clock, 0.22+0.047/0.074/0.048+0.34 ms cpu, 4-&gt;7-&gt;3 MB, 5 MB goal, 12 P
scvg: inuse: 3, idle: 60, sys: 63, released: 56, consumed: 7 (MB)
gc 3 @0.003s 2%: 0.018+0.59+0.011 ms clock, 0.22+0.073/0.008/0.042+0.13 ms cpu, 5-&gt;6-&gt;1 MB, 6 MB goal, 12 P
scvg: 8 KB released
scvg: inuse: 2, idle: 61, sys: 63, released: 56, consumed: 7 (MB)
gc 4 @0.003s 4%: 0.019+0.70+0.054 ms clock, 0.23+0.051/0.047/0.085+0.65 ms cpu, 4-&gt;6-&gt;2 MB, 5 MB goal, 12 P
scvg: 8 KB released
scvg: inuse: 3, idle: 60, sys: 63, released: 56, consumed: 7 (MB)
scvg: 8 KB released
scvg: inuse: 4, idle: 59, sys: 63, released: 56, consumed: 7 (MB)
gc 5 @0.004s 12%: 0.021+0.26+0.49 ms clock, 0.26+0.046/0.037/0.11+5.8 ms cpu, 4-&gt;7-&gt;3 MB, 5 MB goal, 12 P
scvg: inuse: 5, idle: 58, sys: 63, released: 56, consumed: 7 (MB)
gc 6 @0.005s 12%: 0.020+0.17+0.004 ms clock, 0.25+0.080/0.070/0.053+0.051 ms cpu, 5-&gt;6-&gt;1 MB, 6 MB goal, 12 P
scvg: 8 KB released
scvg: inuse: 1, idle: 62, sys: 63, released: 56, consumed: 7 (MB)
</code></pre></div><p>在这个日志中可以观察到两类不同的信息：</p> <div class="language- extra-class"><pre class="language-text"><code>gc 1 @0.000s 2%: 0.009+0.23+0.004 ms clock, 0.11+0.083/0.019/0.14+0.049 ms cpu, 4-&gt;6-&gt;2 MB, 5 MB goal, 12 P
gc 2 @0.001s 2%: 0.018+1.1+0.029 ms clock, 0.22+0.047/0.074/0.048+0.34 ms cpu, 4-&gt;7-&gt;3 MB, 5 MB goal, 12 P
...
</code></pre></div><p>以及：</p> <div class="language- extra-class"><pre class="language-text"><code>scvg: 8 KB released
scvg: inuse: 3, idle: 60, sys: 63, released: 57, consumed: 6 (MB)
scvg: inuse: 3, idle: 60, sys: 63, released: 56, consumed: 7 (MB)
...
</code></pre></div><p>对于用户代码向运行时申请内存产生的垃圾回收：</p> <div class="language- extra-class"><pre class="language-text"><code>gc 2 @0.001s 2%: 0.018+1.1+0.029 ms clock, 0.22+0.047/0.074/0.048+0.34 ms cpu, 4-&gt;7-&gt;3 MB, 5 MB goal, 12 P
</code></pre></div><p>含义由下表所示：</p> <table><thead><tr><th style="text-align:left;">字段</th> <th style="text-align:left;">含义</th></tr></thead> <tbody><tr><td style="text-align:left;">gc 2</td> <td style="text-align:left;">第二个 GC 周期</td></tr> <tr><td style="text-align:left;">0.001</td> <td style="text-align:left;">程序开始后的 0.001 秒</td></tr> <tr><td style="text-align:left;">2%</td> <td style="text-align:left;">该 GC 周期中 CPU 的使用率</td></tr> <tr><td style="text-align:left;">0.018</td> <td style="text-align:left;">标记开始时， STW 所花费的时间（wall clock）</td></tr> <tr><td style="text-align:left;">1.1</td> <td style="text-align:left;">标记过程中，并发标记所花费的时间（wall clock）</td></tr> <tr><td style="text-align:left;">0.029</td> <td style="text-align:left;">标记终止时， STW 所花费的时间（wall clock）</td></tr> <tr><td style="text-align:left;">0.22</td> <td style="text-align:left;">标记开始时， STW 所花费的时间（cpu time）</td></tr> <tr><td style="text-align:left;">0.047</td> <td style="text-align:left;">标记过程中，标记辅助所花费的时间（cpu time）</td></tr> <tr><td style="text-align:left;">0.074</td> <td style="text-align:left;">标记过程中，并发标记所花费的时间（cpu time）</td></tr> <tr><td style="text-align:left;">0.048</td> <td style="text-align:left;">标记过程中，GC 空闲的时间（cpu time）</td></tr> <tr><td style="text-align:left;">0.34</td> <td style="text-align:left;">标记终止时， STW 所花费的时间（cpu time）</td></tr> <tr><td style="text-align:left;">4</td> <td style="text-align:left;">标记开始时，堆的大小的实际值</td></tr> <tr><td style="text-align:left;">7</td> <td style="text-align:left;">标记结束时，堆的大小的实际值</td></tr> <tr><td style="text-align:left;">3</td> <td style="text-align:left;">标记结束时，标记为存活的对象大小</td></tr> <tr><td style="text-align:left;">5</td> <td style="text-align:left;">标记结束时，堆的大小的预测值</td></tr> <tr><td style="text-align:left;">12</td> <td style="text-align:left;">P 的数量</td></tr></tbody></table> <blockquote><p>wall clock 是指开始执行到完成所经历的实际时间，包括其他程序和本程序所消耗的时间；
cpu time 是指特定程序使用 CPU 的时间；
他们存在以下关系：</p> <ul><li>wall clock &lt; cpu time: 充分利用多核</li> <li>wall clock ≈ cpu time: 未并行执行</li> <li>wall clock &gt; cpu time: 多核优势不明显</li></ul></blockquote> <p>对于运行时向操作系统申请内存产生的垃圾回收（向操作系统归还多余的内存）：</p> <div class="language- extra-class"><pre class="language-text"><code>scvg: 8 KB released
scvg: inuse: 3, idle: 60, sys: 63, released: 57, consumed: 6 (MB)
</code></pre></div><p>含义由下表所示：</p> <table><thead><tr><th style="text-align:left;">字段</th> <th style="text-align:left;">含义</th></tr></thead> <tbody><tr><td style="text-align:left;">8 KB released</td> <td style="text-align:left;">向操作系统归还了 8 KB 内存</td></tr> <tr><td style="text-align:left;">3</td> <td style="text-align:left;">已经分配给用户代码、正在使用的总内存大小 (MB)。MB used or partially used spans</td></tr> <tr><td style="text-align:left;">60</td> <td style="text-align:left;">空闲以及等待归还给操作系统的总内存大小（MB）。MB spans pending scavenging</td></tr> <tr><td style="text-align:left;">63</td> <td style="text-align:left;">通知操作系统中保留的内存大小（MB）MB mapped from the system</td></tr> <tr><td style="text-align:left;">57</td> <td style="text-align:left;">已经归还给操作系统的（或者说还未正式申请）的内存大小（MB）。MB released to the system</td></tr> <tr><td style="text-align:left;">6</td> <td style="text-align:left;">已经从操作系统中申请的内存大小（MB）。MB allocated from the system</td></tr></tbody></table> <h3 id="方式2：go-tool-trace"><a href="#方式2：go-tool-trace" class="header-anchor">#</a> 方式2：<code>go tool trace</code></h3> <p><code>go tool trace</code> 的主要功能是将统计而来的信息以一种可视化的方式展示给用户。要使用此工具，可以通过调用 trace API：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	f<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token string">&quot;trace.out&quot;</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> f<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	trace<span class="token punctuation">.</span><span class="token function">Start</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
	<span class="token keyword">defer</span> trace<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>并通过</p> <div class="language- extra-class"><pre class="language-text"><code>$ go tool trace trace.out
2019/12/30 15:50:33 Parsing trace...
2019/12/30 15:50:38 Splitting trace...
2019/12/30 15:50:45 Opening browser. Trace viewer is listening on http://127.0.0.1:51839
</code></pre></div><p>命令来启动可视化界面：</p> <p><img src="/assets/img/gc-trace.5c3091ed.png" alt=""></p> <p>选择第一个链接可以获得如下图示：</p> <p><img src="assets/gc-trace2.png" alt=""></p> <p>右上角的问号可以打开帮助菜单，主要使用方式包括：</p> <ul><li>w/s 键可以用于放大或者缩小视图</li> <li>a/d 键可以用于左右移动</li></ul> <h3 id="方式3：debug-readgcstats"><a href="#方式3：debug-readgcstats" class="header-anchor">#</a> 方式3：<code>debug.ReadGCStats</code></h3> <p>此方式可以通过代码的方式来直接实现对感兴趣指标的监控，例如我们希望每隔一秒钟监控一次 GC 的状态：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">printGCStats</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	t <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">NewTicker</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Second<span class="token punctuation">)</span>
	s <span class="token operator">:=</span> debug<span class="token punctuation">.</span>GCStats<span class="token punctuation">{</span><span class="token punctuation">}</span>
	<span class="token keyword">for</span> <span class="token punctuation">{</span>
		<span class="token keyword">select</span> <span class="token punctuation">{</span>
		<span class="token keyword">case</span> <span class="token operator">&lt;-</span>t<span class="token punctuation">.</span>C<span class="token punctuation">:</span>
			debug<span class="token punctuation">.</span><span class="token function">ReadGCStats</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span>
			fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;gc %d last@%v, PauseTotal %v\n&quot;</span><span class="token punctuation">,</span> s<span class="token punctuation">.</span>NumGC<span class="token punctuation">,</span> s<span class="token punctuation">.</span>LastGC<span class="token punctuation">,</span> s<span class="token punctuation">.</span>PauseTotal<span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">go</span> <span class="token function">printGCStats</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>我们能够看到如下输出：</p> <div class="language-go extra-class"><pre class="language-go"><code>$ <span class="token keyword">go</span> run main<span class="token punctuation">.</span><span class="token keyword">go</span>

gc <span class="token number">4954</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">19</span><span class="token punctuation">:</span><span class="token number">37.505575</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> PauseTotal <span class="token number">29.901171</span>ms
gc <span class="token number">9195</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">19</span><span class="token punctuation">:</span><span class="token number">38.50565</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> PauseTotal <span class="token number">77.579622</span>ms
gc <span class="token number">13502</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">19</span><span class="token punctuation">:</span><span class="token number">39.505714</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> PauseTotal <span class="token number">128.022307</span>ms
gc <span class="token number">17555</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">19</span><span class="token punctuation">:</span><span class="token number">40.505579</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> PauseTotal <span class="token number">182.816528</span>ms
gc <span class="token number">21838</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">19</span><span class="token punctuation">:</span><span class="token number">41.505595</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> PauseTotal <span class="token number">246.618502</span>ms
</code></pre></div><h3 id="方式4：runtime-readmemstats"><a href="#方式4：runtime-readmemstats" class="header-anchor">#</a> 方式4：<code>runtime.ReadMemStats</code></h3> <p>除了使用 debug 包提供的方法外，还可以直接通过运行时的内存相关的 API 进行监控：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">printMemStats</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	t <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">NewTicker</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span>Second<span class="token punctuation">)</span>
	s <span class="token operator">:=</span> runtime<span class="token punctuation">.</span>MemStats<span class="token punctuation">{</span><span class="token punctuation">}</span>

	<span class="token keyword">for</span> <span class="token punctuation">{</span>
		<span class="token keyword">select</span> <span class="token punctuation">{</span>
		<span class="token keyword">case</span> <span class="token operator">&lt;-</span>t<span class="token punctuation">.</span>C<span class="token punctuation">:</span>
			runtime<span class="token punctuation">.</span><span class="token function">ReadMemStats</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>s<span class="token punctuation">)</span>
			fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;gc %d last@%v, next_heap_size@%vMB\n&quot;</span><span class="token punctuation">,</span> s<span class="token punctuation">.</span>NumGC<span class="token punctuation">,</span> time<span class="token punctuation">.</span><span class="token function">Unix</span><span class="token punctuation">(</span><span class="token function">int64</span><span class="token punctuation">(</span>time<span class="token punctuation">.</span><span class="token function">Duration</span><span class="token punctuation">(</span>s<span class="token punctuation">.</span>LastGC<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Seconds</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span> s<span class="token punctuation">.</span>NextGC<span class="token operator">/</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token operator">&lt;&lt;</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">go</span> <span class="token function">printMemStats</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><div class="language-go extra-class"><pre class="language-go"><code>$ <span class="token keyword">go</span> run main<span class="token punctuation">.</span><span class="token keyword">go</span>

gc <span class="token number">4887</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">44</span><span class="token punctuation">:</span><span class="token number">56</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> next_heap_size@<span class="token number">4</span>MB
gc <span class="token number">10049</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">44</span><span class="token punctuation">:</span><span class="token number">57</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> next_heap_size@<span class="token number">4</span>MB
gc <span class="token number">15231</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">44</span><span class="token punctuation">:</span><span class="token number">58</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> next_heap_size@<span class="token number">4</span>MB
gc <span class="token number">20378</span> last@<span class="token number">2019</span><span class="token operator">-</span><span class="token number">12</span><span class="token operator">-</span><span class="token number">30</span> <span class="token number">15</span><span class="token punctuation">:</span><span class="token number">44</span><span class="token punctuation">:</span><span class="token number">59</span> <span class="token operator">+</span><span class="token number">0100</span> CET<span class="token punctuation">,</span> next_heap_size@<span class="token number">6</span>MB
</code></pre></div><p>当然，后两种方式能够监控的指标很多，读者可以自行查看 <a href="https://golang.org/pkg/runtime/debug/#GCStats" target="_blank" rel="noopener noreferrer"><code>debug.GCStats</code><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a> 和
<a href="https://golang.org/pkg/runtime/#MemStats" target="_blank" rel="noopener noreferrer"><code>runtime.MemStats</code><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a> 的字段，这里不再赘述。</p> <h2 id="_7-有了-gc，为什么还会发生内存泄露？"><a href="#_7-有了-gc，为什么还会发生内存泄露？" class="header-anchor">#</a> 7. 有了 GC，为什么还会发生内存泄露？</h2> <p>在一个具有 GC 的语言中，我们常说的内存泄漏，用严谨的话来说应该是：预期的能很快被释放的内存由于附着在了长期存活的内存上、或生命期意外地被延长，导致预计能够立即回收的内存而长时间得不到回收。</p> <p>在 Go 中，由于 goroutine 的存在，所谓的内存泄漏除了附着在长期对象上之外，还存在多种不同的形式。</p> <h3 id="形式1：预期能被快速释放的内存因被根对象引用而没有得到迅速释放"><a href="#形式1：预期能被快速释放的内存因被根对象引用而没有得到迅速释放" class="header-anchor">#</a> 形式1：预期能被快速释放的内存因被根对象引用而没有得到迅速释放</h3> <p>当有一个全局对象时，可能不经意间将某个变量附着在其上，且忽略的将其进行释放，则该内存永远不会得到释放。例如：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">var</span> cache <span class="token operator">=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">]</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">keepalloc</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10000</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		m <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token operator">&lt;&lt;</span><span class="token number">10</span><span class="token punctuation">)</span>
		cache<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> m
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><h3 id="形式2：goroutine-泄漏"><a href="#形式2：goroutine-泄漏" class="header-anchor">#</a> 形式2：goroutine 泄漏</h3> <p>Goroutine 作为一种逻辑上理解的轻量级线程，需要维护执行用户代码的上下文信息。在运行过程中也需要消耗一定的内存来保存这类信息，而这些内存在目前版本的 Go 中是不会被释放的。因此，如果一个程序持续不断地产生新的 goroutine、且不结束已经创建的 goroutine 并复用这部分内存，就会造成内存泄漏的现象，例如：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">keepalloc2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">100000</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token keyword">select</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
		<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><h3 id="验证"><a href="#验证" class="header-anchor">#</a> 验证</h3> <p>我们可以通过如下形式来调用上述两个函数：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;os&quot;</span>
	<span class="token string">&quot;runtime/trace&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	f<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token string">&quot;trace.out&quot;</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> f<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	trace<span class="token punctuation">.</span><span class="token function">Start</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
	<span class="token keyword">defer</span> trace<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token function">keepalloc</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token function">keepalloc2</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>运行程序：</p> <div class="language-shell extra-class"><pre class="language-shell"><code>go run main.go
</code></pre></div><p>会看到程序中生成了 <code>trace.out</code> 文件，我们可以使用 <code>go tool trace trace.out</code> 命令得到下图：</p> <p><img src="/assets/img/gc-leak1.7e07cef1.png" alt=""></p> <p>可以看到，途中的 Heap 在持续增长，没有内存被回收，产生了内存泄漏的现象。</p> <p>值得一提的是，这种形式的 goroutine 泄漏还可能由 channel 泄漏导致。而 channel 的泄漏本质上与 goroutine 泄漏存在直接联系。Channel 作为一种同步原语，会连接两个不同的 goroutine，如果一个 goroutine 尝试向一个没有接收方的无缓冲 channel 发送消息，则该 goroutine 会被永久的休眠，整个 goroutine 及其执行栈都得不到释放，例如：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">var</span> ch <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">keepalloc3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">100000</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token comment">// 没有接收方，goroutine 会一直阻塞</span>
		<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> ch <span class="token operator">&lt;-</span> <span class="token keyword">struct</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">{</span><span class="token punctuation">}</span> <span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><h2 id="_8-并发标记清除法的难点是什么？"><a href="#_8-并发标记清除法的难点是什么？" class="header-anchor">#</a> 8. 并发标记清除法的难点是什么？</h2> <p>在没有用户态代码并发修改<code>三色抽象</code>的情况下，回收可以正常结束。但是并发回收的根本问题在于，用户态代码在回收过程中会并发地更新对象图，从而造成赋值器和回收器可能对对象图的结构产生不同的认知。这时以一个固定的三色波面作为回收过程前进的边界则不再合理。</p> <p>我们不妨考虑赋值器写操作的例子：</p> <table><thead><tr><th>时序</th> <th>回收器</th> <th>赋值器</th> <th>说明</th></tr></thead> <tbody><tr><td>1</td> <td>shade(A, gray)</td> <td></td> <td>回收器：根对象的子节点着色为灰色对象</td></tr> <tr><td>2</td> <td>shade(C, black)</td> <td></td> <td>回收器：当所有子节点着色为灰色后，将节点着为黑色</td></tr> <tr><td>3</td> <td></td> <td>C.ref3 = C.ref2.ref1</td> <td>赋值器：并发的修改了 C 的子节点</td></tr> <tr><td>4</td> <td></td> <td>A.ref1 = nil</td> <td>赋值器：并发的修改了 A 的子节点</td></tr> <tr><td>5</td> <td>shade(A.ref1, gray)</td> <td></td> <td>回收器：进一步灰色对象的子节点并着色为灰色对象，这时由于 <code>A.ref1</code> 为 <code>nil</code>，什么事情也没有发生</td></tr> <tr><td>6</td> <td>shade(A, black)</td> <td></td> <td>回收器：由于所有子节点均已标记，回收器也不会重新扫描已经被标记为黑色的对象，此时 A 被着色为黑色，<code>scan(A)</code> 什么也不会发生，进而 B 在此次回收过程中永远不会被标记为黑色，进而错误地被回收。</td></tr></tbody></table> <ul><li>初始状态：假设某个黑色对象 C 指向某个灰色对象 A ，而 A 指向白色对象 B；</li> <li><code>C.ref3 = C.ref2.ref1</code>：赋值器并发地将黑色对象 C 指向（ref3）了白色对象 B；</li> <li><code>A.ref1 = nil</code>：移除灰色对象 A 对白色对象 B 的引用（ref2）；</li> <li>最终状态：在继续扫描的过程中，白色对象 B 永远不会被标记为黑色对象了（回收器不会重新扫描黑色对象），进而对象 B 被错误地回收。</li></ul> <p><img src="/assets/img/gc-mutator.9369dcf0.png" alt="gc-mutator"></p> <p>总而言之，并发标记清除中面临的一个根本问题就是如何保证标记与清除过程的正确性。</p> <h2 id="_9-什么是写屏障、混合写屏障，如何实现？"><a href="#_9-什么是写屏障、混合写屏障，如何实现？" class="header-anchor">#</a> 9. 什么是写屏障、混合写屏障，如何实现？</h2> <p>要讲清楚写屏障，就需要理解三色标记清除算法中的<strong>强弱不变性</strong>以及<strong>赋值器的颜色</strong>，理解他们需要一定的抽象思维。写屏障是一个在并发垃圾回收器中才会出现的概念，垃圾回收器的正确性体现在：<strong>不应出现对象的丢失，也不应错误的回收还不需要回收的对象。</strong></p> <p>可以证明，当以下两个条件同时满足时会破坏垃圾回收器的正确性：</p> <ul><li><strong>条件 1</strong>: 赋值器修改对象图，导致某一黑色对象引用白色对象；</li> <li><strong>条件 2</strong>: 从灰色对象出发，到达白色对象的、未经访问过的路径被赋值器破坏。</li></ul> <p>只要能够避免其中任何一个条件，则不会出现对象丢失的情况，因为：</p> <ul><li>如果条件 1 被避免，则所有白色对象均被灰色对象引用，没有白色对象会被遗漏；</li> <li>如果条件 2 被避免，即便白色对象的指针被写入到黑色对象中，但从灰色对象出发，总存在一条没有访问过的路径，从而找到到达白色对象的路径，白色对象最终不会被遗漏。</li></ul> <p>我们不妨将三色不变性所定义的波面根据这两个条件进行削弱：</p> <ul><li>当满足原有的三色不变性定义（或上面的两个条件都不满足时）的情况称为<strong>强三色不变性（strong tricolor invariant）</strong></li> <li>当赋值器令黑色对象引用白色对象时（满足条件 1 时）的情况称为<strong>弱三色不变性（weak tricolor invariant）</strong></li></ul> <p>当赋值器进一步破坏灰色对象到达白色对象的路径时（进一步满足条件 2 时），即打破弱三色不变性，也就破坏了回收器的正确性；或者说，在破坏强弱三色不变性时必须引入额外的辅助操作。弱三色不变形的好处在于：<strong>只要存在未访问的能够到达白色对象的路径，就可以将黑色对象指向白色对象。</strong></p> <p>如果我们考虑并发的用户态代码，回收器不允许同时停止所有赋值器，就是涉及了存在的多个不同状态的赋值器。为了对概念加以明确，还需要换一个角度，把回收器视为对象，把赋值器视为影响回收器这一对象的实际行为（即影响 GC 周期的长短），从而引入赋值器的颜色：</p> <ul><li>黑色赋值器：已经由回收器扫描过，不会再次对其进行扫描。</li> <li>灰色赋值器：尚未被回收器扫描过，或尽管已经扫描过但仍需要重新扫描。</li></ul> <p>赋值器的颜色对回收周期的结束产生影响：</p> <ul><li>如果某种并发回收器允许灰色赋值器的存在，则必须在回收结束之前重新扫描对象图。</li> <li>如果重新扫描过程中发现了新的灰色或白色对象，回收器还需要对新发现的对象进行追踪，但是在新追踪的过程中，赋值器仍然可能在其根中插入新的非黑色的引用，如此往复，直到重新扫描过程中没有发现新的白色或灰色对象。</li></ul> <p>于是，在允许灰色赋值器存在的算法，最坏的情况下，回收器只能将所有赋值器线程停止才能完成其跟对象的完整扫描，也就是我们所说的 STW。</p> <p>为了确保强弱三色不变性的并发指针更新操作，需要通过赋值器屏障技术来保证指针的读写操作一致。因此我们所说的 Go 中的写屏障、混合写屏障，其实是指赋值器的写屏障，赋值器的写屏障用来保证赋值器在进行指针写操作时，不会破坏弱三色不变性。</p> <p>有两种非常经典的写屏障：Dijkstra 插入屏障和 Yuasa 删除屏障。</p> <p>灰色赋值器的 Dijkstra 插入屏障的基本思想是避免满足条件 1：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token comment">// 灰色赋值器 Dijkstra 插入屏障</span>
<span class="token keyword">func</span> <span class="token function">DijkstraWritePointer</span><span class="token punctuation">(</span>slot <span class="token operator">*</span>unsafe<span class="token punctuation">.</span>Pointer<span class="token punctuation">,</span> ptr unsafe<span class="token punctuation">.</span>Pointer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">shade</span><span class="token punctuation">(</span>ptr<span class="token punctuation">)</span>
    <span class="token operator">*</span>slot <span class="token operator">=</span> ptr
<span class="token punctuation">}</span>
</code></pre></div><p>为了防止黑色对象指向白色对象，应该假设 <code>*slot</code> 可能会变为黑色，为了确保 <code>ptr</code> 不会在被赋值到 <code>*slot</code> 前变为白色，<code>shade(ptr)</code> 会先将指针 <code>ptr</code> 标记为灰色，进而避免了条件 1。但是，由于并不清楚赋值器以后会不会将这个引用删除，因此还需要重新扫描来重新确定关系图，这时需要 STW，如图所示：</p> <p><img src="/assets/img/gc-wb-dijkstra.64bb727e.png" alt=""></p> <p>Dijkstra 插入屏障的好处在于可以立刻开始并发标记，但由于产生了灰色赋值器，缺陷是需要标记终止阶段 STW 时进行重新扫描。</p> <p>黑色赋值器的 Yuasa 删除屏障的基本思想是避免满足条件 2：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token comment">// 黑色赋值器 Yuasa 屏障</span>
<span class="token keyword">func</span> <span class="token function">YuasaWritePointer</span><span class="token punctuation">(</span>slot <span class="token operator">*</span>unsafe<span class="token punctuation">.</span>Pointer<span class="token punctuation">,</span> ptr unsafe<span class="token punctuation">.</span>Pointer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">shade</span><span class="token punctuation">(</span><span class="token operator">*</span>slot<span class="token punctuation">)</span>
    <span class="token operator">*</span>slot <span class="token operator">=</span> ptr
<span class="token punctuation">}</span>
</code></pre></div><p>为了防止丢失从灰色对象到白色对象的路径，应该假设 <code>*slot</code> 可能会变为黑色，为了确保 <code>ptr</code> 不会在被赋值到 <code>*slot</code> 前变为白色，<code>shade(*slot)</code> 会先将 <code>*slot</code> 标记为灰色，进而该写操作总是创造了一条灰色到灰色或者灰色到白色对象的路径，进而避免了条件 2。</p> <p>Yuasa 删除屏障的优势则在于不需要标记结束阶段的重新扫描，缺陷是依然会产生丢失的对象，需要在标记开始前对整个对象图进行快照。</p> <p><img src="/assets/img/gc-wb-yuasa.4bf313b4.png" alt=""></p> <p>Go 在 1.8 的时候为了简化 GC 的流程，同时减少标记终止阶段的重扫成本，将 Dijkstra 插入屏障和 Yuasa 删除屏障进行混合，形成混合写屏障。该屏障提出时的基本思想是：<strong>对正在被覆盖的对象进行着色，且如果当前栈未扫描完成，则同样对指针进行着色。</strong></p> <p>但在最终实现时<a href="https://github.com/golang/proposal/blob/master/design/17503-eliminate-rescan.md" target="_blank" rel="noopener noreferrer">原提案<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>中对 <code>ptr</code> 的着色还额外包含对执行栈的着色检查，但由于时间有限，并未完整实现过，所以混合写屏障在目前的实现伪代码是：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token comment">// 混合写屏障</span>
<span class="token keyword">func</span> <span class="token function">HybridWritePointerSimple</span><span class="token punctuation">(</span>slot <span class="token operator">*</span>unsafe<span class="token punctuation">.</span>Pointer<span class="token punctuation">,</span> ptr unsafe<span class="token punctuation">.</span>Pointer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">shade</span><span class="token punctuation">(</span><span class="token operator">*</span>slot<span class="token punctuation">)</span>
	  <span class="token function">shade</span><span class="token punctuation">(</span>ptr<span class="token punctuation">)</span>
    <span class="token operator">*</span>slot <span class="token operator">=</span> ptr
<span class="token punctuation">}</span>
</code></pre></div><p>在这个实现中，如果无条件对引用双方进行着色，自然结合了 Dijkstra 和 Yuasa 写屏障的优势，但缺点也非常明显，因为着色成本是双倍的，而且编译器需要插入的代码也成倍增加，随之带来的结果就是编译后的二进制文件大小也进一步增加。为了针对写屏障的性能进行优化，Go 1.10 前后，Go 团队随后实现了批量写屏障机制。其基本想法是将需要着色的指针同一写入一个缓存，每当缓存满时统一对缓存中的所有 <code>ptr</code> 指针进行着色。</p> <h1 id="gc-的实现细节"><a href="#gc-的实现细节" class="header-anchor">#</a> GC 的实现细节</h1> <h2 id="_10-go-语言中-gc-的流程是什么？"><a href="#_10-go-语言中-gc-的流程是什么？" class="header-anchor">#</a> 10. Go 语言中 GC 的流程是什么？</h2> <p>当前版本的 Go 以 STW 为界限，可以将 GC 划分为五个阶段：</p> <table><thead><tr><th style="text-align:center;">阶段</th> <th style="text-align:center;">说明</th> <th style="text-align:center;">赋值器状态</th></tr></thead> <tbody><tr><td style="text-align:center;">GCMark</td> <td style="text-align:center;">标记准备阶段，为并发标记做准备工作，启动写屏障</td> <td style="text-align:center;">STW</td></tr> <tr><td style="text-align:center;">GCMark</td> <td style="text-align:center;">扫描标记阶段，与赋值器并发执行，写屏障开启</td> <td style="text-align:center;">并发</td></tr> <tr><td style="text-align:center;">GCMarkTermination</td> <td style="text-align:center;">标记终止阶段，保证一个周期内标记任务完成，停止写屏障</td> <td style="text-align:center;">STW</td></tr> <tr><td style="text-align:center;">GCoff</td> <td style="text-align:center;">内存清扫阶段，将需要回收的内存归还到堆中，写屏障关闭</td> <td style="text-align:center;">并发</td></tr> <tr><td style="text-align:center;">GCoff</td> <td style="text-align:center;">内存归还阶段，将过多的内存归还给操作系统，写屏障关闭</td> <td style="text-align:center;">并发</td></tr></tbody></table> <p>具体而言，各个阶段的触发函数分别为：</p> <p><img src="https://user-images.githubusercontent.com/7698088/71047691-930aba00-2177-11ea-84d5-4e9eac2df723.png" alt="gc-process"></p> <h2 id="_11-触发-gc-的时机是什么？"><a href="#_11-触发-gc-的时机是什么？" class="header-anchor">#</a> 11. 触发 GC 的时机是什么？</h2> <p>Go 语言中对 GC 的触发时机存在两种形式：</p> <ol><li><p><strong>主动触发</strong>，通过调用 runtime.GC 来触发 GC，此调用阻塞式地等待当前 GC 运行完毕。</p></li> <li><p><strong>被动触发</strong>，分为两种方式：</p> <ul><li><p>使用系统监控，当超过两分钟没有产生任何 GC 时，强制触发 GC。</p></li> <li><p>使用步调（Pacing）算法，其核心思想是控制内存增长的比例。</p></li></ul></li></ol> <p>通过 <code>GOGC</code> 或者 <code>debug.SetGCPercent</code> 进行控制（他们控制的是同一个变量，即堆的增长率 $\rho$）。整个算法的设计考虑的是优化问题：如果设上一次 GC 完成时，内存的数量为 $H_m$（heap marked），估计需要触发 GC 时的堆大小 $H_T$（heap trigger），使得完成 GC 时候的目标堆大小 $H_g$（heap goal） 与实际完成时候的堆大小 $H_a$（heap actual）最为接近，即： $\min |H_g - H_a| = \min|(1+\rho)H_m - H_a|$。</p> <p><img src="https://user-images.githubusercontent.com/7698088/71047935-5e4b3280-2178-11ea-9abd-c86667ac9f88.png" alt="gc-pacing"></p> <p>除此之外，步调算法还需要考虑 CPU 利用率的问题，显然我们不应该让垃圾回收器占用过多的 CPU，即不应该让每个负责执行用户 goroutine 的线程都在执行标记过程。理想情况下，在用户代码满载的时候，GC 的 CPU 使用率不应该超过 25%，即另一个优化问题：如果设 $u_g$为目标 CPU 使用率（goal utilization），而 $u_a$为实际 CPU 使用率（actual utilization），则 $\min|u_g - u_a|$。</p> <blockquote><p>求解这两个优化问题的具体数学建模过程我们不在此做深入讨论，有兴趣的读者可以参考两个设计文档：<a href="https://docs.google.com/document/d/1wmjrocXIWTr1JxU-3EQBI6BK6KgtiFArkG47XK73xIQ/edit#" target="_blank" rel="noopener noreferrer">Go 1.5 concurrent garbage collector pacing<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a> 和 <a href="https://github.com/golang/proposal/blob/master/design/14951-soft-heap-limit.md" target="_blank" rel="noopener noreferrer">Separate soft and hard heap size goal<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>。</p></blockquote> <p>计算 $H_T$ 的最终结论（从 Go 1.10 时开始 $h_t$ 增加了上界 $0.95 \rho$，从 Go 1.14 开始时 $h_t$ 增加了下界 0.6）是：</p> <ul><li>设第 n 次触发 GC 时 (n &gt; 1)，估计得到的堆增长率为 $h_t^{(n)}$、运行过程中的实际堆增长率为 $h_a^{(n)}$，用户设置的增长率为 $\rho = \text{GOGC}/100$（ $\rho &gt; 0$）则第 $n+1$ 次出触发 GC 时候，估计的堆增长率为：</li></ul> <p>$$
h_t^{(n+1)} = h_t^{(n)} + 0.5 \left[ \frac{H_g^{(n)} - H_a^{(n)}}{H_a^{(n)}} - h_t^{(n)} - \frac{u_a^{(n)}}{u_g^{(n)}} \left( h_a^{(n)} - h_t^{(n)} \right) \right]
$$</p> <ul><li><p>特别的，$h_t^{(1)} = 7 / 8$，$u_a^{(1)} = 0.25$，$u_g^{(1)} = 0.3$。第一次触发 GC 时，如果当前的堆小于 $4\rho$ MB，则强制调整到 $4\rho$ MB 时触发 GC</p></li> <li><p>特别的，当 $h_t^{(n)}&lt;0.6$时，将其调整为 $0.6$，当 $h_t^{(n)} &gt; 0.95 \rho$ 时，将其设置为 $0.95 \rho$</p></li> <li><p>默认情况下，$\rho = 1$（即 GOGC = 100），第一次触发 GC 时强制设置触发第一次 GC 为 4MB，可以写如下程序进行验证：</p></li></ul> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;os&quot;</span>
	<span class="token string">&quot;runtime&quot;</span>
	<span class="token string">&quot;runtime/trace&quot;</span>
	<span class="token string">&quot;sync/atomic&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">var</span> stop <span class="token builtin">uint64</span>

<span class="token comment">// 通过对象 P 的释放状态，来确定 GC 是否已经完成</span>
<span class="token keyword">func</span> <span class="token function">gcfinished</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span><span class="token builtin">int</span> <span class="token punctuation">{</span>
	p <span class="token operator">:=</span> <span class="token number">1</span>
	runtime<span class="token punctuation">.</span><span class="token function">SetFinalizer</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>p<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token boolean">_</span> <span class="token operator">*</span><span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;gc finished&quot;</span><span class="token punctuation">)</span>
		atomic<span class="token punctuation">.</span><span class="token function">StoreUint64</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stop<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token comment">// 通知停止分配</span>
	<span class="token punctuation">}</span><span class="token punctuation">)</span>
	<span class="token keyword">return</span> <span class="token operator">&amp;</span>p
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">allocate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token comment">// 每次调用分配 0.25MB</span>
	<span class="token boolean">_</span> <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token function">int</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token operator">&lt;&lt;</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token operator">*</span><span class="token number">0.25</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	f<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token string">&quot;trace.out&quot;</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> f<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	trace<span class="token punctuation">.</span><span class="token function">Start</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
	<span class="token keyword">defer</span> trace<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token function">gcfinished</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token comment">// 当完成 GC 时停止分配</span>
	<span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">1</span><span class="token punctuation">;</span> atomic<span class="token punctuation">.</span><span class="token function">LoadUint64</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stop<span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token number">1</span><span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;#allocate: &quot;</span><span class="token punctuation">,</span> n<span class="token punctuation">)</span>
		<span class="token function">allocate</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;terminate&quot;</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>我们先来验证最简单的一种情况，即第一次触发 GC 时的堆大小：</p> <div class="language- extra-class"><pre class="language-text"><code>$ go build -o main
$ GODEBUG=gctrace=1 ./main
#allocate:  1
(...)
#allocate:  20
gc finished
gc 1 @0.001s 3%: 0.016+0.23+0.019 ms clock, 0.20+0.11/0.060/0.13+0.22 ms cpu, 4-&gt;5-&gt;1 MB, 5 MB goal, 12 P
scvg: 8 KB released
scvg: inuse: 1, idle: 62, sys: 63, released: 58, consumed: 5 (MB)
terminate
</code></pre></div><p>通过这一行数据我们可以看到：</p> <div class="language- extra-class"><pre class="language-text"><code>gc 1 @0.001s 3%: 0.016+0.23+0.019 ms clock, 0.20+0.11/0.060/0.13+0.22 ms cpu, 4-&gt;5-&gt;1 MB, 5 MB goal, 12 P
</code></pre></div><ol><li>程序在完成第一次 GC 后便终止了程序，符合我们的设想</li> <li>第一次 GC 开始时的堆大小为 4MB，符合我们的设想</li> <li>当标记终止时，堆大小为 5MB，此后开始执行清扫，这时分配执行到第 20 次，即 20*0.25 = 5MB，符合我们的设想</li></ol> <p>我们将分配次数调整到 50 次</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">1</span><span class="token punctuation">;</span> n <span class="token operator">&lt;</span> <span class="token number">50</span><span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
	<span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;#allocate: &quot;</span><span class="token punctuation">,</span> n<span class="token punctuation">)</span>
	<span class="token function">allocate</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>来验证第二次 GC 触发时是否满足公式所计算得到的值（为 GODEBUG 进一步设置 <code>gcpacertrace=1</code>）：</p> <div class="language- extra-class"><pre class="language-text"><code>$ go build -o main
$ GODEBUG=gctrace=1,gcpacertrace=1 ./main
#allocate:  1
(...)

pacer: H_m_prev=2236962 h_t=+8.750000e-001 H_T=4194304 h_a=+2.387451e+000 H_a=7577600 h_g=+1.442627e+000 H_g=5464064 u_a=+2.652227e-001 u_g=+3.000000e-001 W_a=152832 goalΔ=+5.676271e-001 actualΔ=+1.512451e+000 u_a/u_g=+8.840755e-001
#allocate:  28
gc 1 @0.001s 5%: 0.032+0.32+0.055 ms clock, 0.38+0.068/0.053/0.11+0.67 ms cpu, 4-&gt;7-&gt;3 MB, 5 MB goal, 12 P

(...)
#allocate:  37
pacer: H_m_prev=3307736 h_t=+6.000000e-001 H_T=5292377 h_a=+7.949171e-001 H_a=5937112 h_g=+1.000000e+000 H_g=6615472 u_a=+2.658428e-001 u_g=+3.000000e-001 W_a=154240 goalΔ=+4.000000e-001 actualΔ=+1.949171e-001 u_a/u_g=+8.861428e-001
#allocate:  38
gc 2 @0.002s 9%: 0.017+0.26+0.16 ms clock, 0.20+0.079/0.058/0.12+1.9 ms cpu, 5-&gt;5-&gt;0 MB, 6 MB goal, 12 P
</code></pre></div><p>我们可以得到数据：</p> <ul><li>第一次估计得到的堆增长率为 $h_t^{(1)} = 0.875$</li> <li>第一次的运行过程中的实际堆增长率为 $h_a^{(1)} = 0.2387451$</li> <li>第一次实际的堆大小为 $H_a^{(1)}=7577600$</li> <li>第一次目标的堆大小为 $H_g^{(1)}=5464064$</li> <li>第一次的 CPU 实际使用率为 $u_a^{(1)} = 0.2652227$</li> <li>第一次的 CPU 目标使用率为 $u_g^{(1)} = 0.3$</li></ul> <p>我们据此计算第二次估计的堆增长率：</p> <p>$$
\begin{align}
h_t^{(2)} &amp;= h_t^{(1)} + 0.5 \left[ \frac{H_g^{(1)} - H_a^{(1)}}{H_a^{(1)}} - h_t^{(1)} - \frac{u_a^{(1)}}{u_g^{(1)}} \left( h_a^{(1)} - h_t^{(1)} \right) \right] \
&amp;= 0.875 + 0.5 \left[ \frac{5464064 - 7577600}{5464064} - 0.875 - \frac{0.2652227}{0.3} \left( 0.2387451 - 0.875 \right) \right] \
&amp; \approx 0.52534543909 \
\end{align}
$$</p> <p>因为 $0.52534543909 &lt; 0.6\rho = 0.6$，因此下一次的触发率为 $h_t^{2} = 0.6$，与我们实际观察到的第二次 GC 的触发率 0.6 吻合。</p> <h2 id="_12-如果内存分配速度超过了标记清除的速度怎么办？"><a href="#_12-如果内存分配速度超过了标记清除的速度怎么办？" class="header-anchor">#</a> 12. 如果内存分配速度超过了标记清除的速度怎么办？</h2> <p>目前的 Go 实现中，当 GC 触发后，会首先进入并发标记的阶段。并发标记会设置一个标志，并在 mallocgc 调用时进行检查。当存在新的内存分配时，会暂停分配内存过快的那些 goroutine，并将其转去执行一些辅助标记（Mark Assist）的工作，从而达到放缓继续分配、辅助 GC 的标记工作的目的。</p> <p>编译器会分析用户代码，并在需要分配内存的位置，将申请内存的操作翻译为 <code>mallocgc</code> 调用，而 <code>mallocgc</code> 的实现决定了标记辅助的实现，其伪代码思路如下：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">mallocgc</span><span class="token punctuation">(</span>t typ<span class="token punctuation">.</span>Type<span class="token punctuation">,</span> size <span class="token builtin">uint64</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">if</span> enableMarkAssist <span class="token punctuation">{</span>
		<span class="token comment">// 进行标记辅助，此时用户代码没有得到执行</span>
		<span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token comment">// 执行内存分配</span>
	<span class="token punctuation">(</span><span class="token operator">...</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><h1 id="gc-的优化问题"><a href="#gc-的优化问题" class="header-anchor">#</a> GC 的优化问题</h1> <h2 id="_13-gc-关注的指标有哪些？"><a href="#_13-gc-关注的指标有哪些？" class="header-anchor">#</a> 13. GC 关注的指标有哪些？</h2> <p>Go 的 GC 被设计为成比例触发、大部分工作与赋值器并发、不分代、无内存移动且会主动向操作系统归还申请的内存。因此最主要关注的、能够影响赋值器的性能指标有：</p> <ul><li>CPU 利用率：回收算法会在多大程度上拖慢程序？有时候，这个是通过回收占用的 CPU 时间与其它 CPU 时间的百分比来描述的。</li> <li>GC 停顿时间：回收器会造成多长时间的停顿？目前的 GC 中需要考虑 STW 和 Mark Assist 两个部分可能造成的停顿。</li> <li>GC 停顿频率：回收器造成的停顿频率是怎样的？目前的 GC 中需要考虑 STW 和 Mark Assist 两个部分可能造成的停顿。</li> <li>GC 可扩展性：当堆内存变大时，垃圾回收器的性能如何？但大部分的程序可能并不一定关心这个问题。</li></ul> <h2 id="_14-go-的-gc-如何调优？"><a href="#_14-go-的-gc-如何调优？" class="header-anchor">#</a> 14. Go 的 GC 如何调优？</h2> <p>Go 的 GC 被设计为极致简洁，与较为成熟的 Java GC 的数十个可控参数相比，严格意义上来讲，Go 可供用户调整的参数只有 GOGC 环境变量。当我们谈论 GC 调优时，通常是指减少用户代码对 GC 产生的压力，这一方面包含了减少用户代码分配内存的数量（即对程序的代码行为进行调优），另一方面包含了最小化 Go 的 GC 对 CPU 的使用率（即调整 GOGC）。</p> <p>GC 的调优是在特定场景下产生的，并非所有程序都需要针对 GC 进行调优。只有那些对执行延迟非常敏感、
当 GC 的开销成为程序性能瓶颈的程序，才需要针对 GC 进行性能调优，几乎不存在于实际开发中 99% 的情况。
除此之外，Go 的 GC 也仍然有一定的可改进的空间，也有部分 GC 造成的问题，目前仍属于 Open Problem。</p> <p>总的来说，我们可以在现在的开发中处理的有以下几种情况：</p> <ol><li>对停顿敏感：GC 过程中产生的长时间停顿、或由于需要执行 GC 而没有执行用户代码，导致需要立即执行的用户代码执行滞后。</li> <li>对资源消耗敏感：对于频繁分配内存的应用而言，频繁分配内存增加 GC 的工作量，原本可以充分利用 CPU 的应用不得不频繁地执行垃圾回收，影响用户代码对 CPU 的利用率，进而影响用户代码的执行效率。</li></ol> <p>从这两点来看，所谓 GC 调优的核心思想也就是充分的围绕上面的两点来展开：优化内存的申请速度，尽可能的少申请内存，复用已申请的内存。或者简单来说，不外乎这三个关键字：<strong>控制、减少、复用</strong>。</p> <p>我们将通过三个实际例子介绍如何定位 GC 的存在的问题，并一步一步进行性能调优。当然，在实际情况中问题远比这些例子要复杂，这里也只是讨论调优的核心思想，更多的时候也只能具体问题具体分析。</p> <h3 id="例1：合理化内存分配的速度、提高赋值器的-cpu-利用率"><a href="#例1：合理化内存分配的速度、提高赋值器的-cpu-利用率" class="header-anchor">#</a> 例1：合理化内存分配的速度、提高赋值器的 CPU 利用率</h3> <p>我们来看这样一个例子。在这个例子中，<code>concat</code> 函数负责拼接一些长度不确定的字符串。并且为了快速完成任务，出于某种原因，在两个嵌套的 for 循环中一口气创建了 800 个 goroutine。在 main 函数中，启动了一个 goroutine 并在程序结束前不断的触发 GC，并尝试输出 GC 的平均执行时间：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;os&quot;</span>
	<span class="token string">&quot;runtime&quot;</span>
	<span class="token string">&quot;runtime/trace&quot;</span>
	<span class="token string">&quot;sync/atomic&quot;</span>
	<span class="token string">&quot;time&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">var</span> <span class="token punctuation">(</span>
	stop  <span class="token builtin">int32</span>
	count <span class="token builtin">int64</span>
	sum   time<span class="token punctuation">.</span>Duration
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> n <span class="token operator">&lt;</span> <span class="token number">100</span><span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">8</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
			<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
				s <span class="token operator">:=</span> <span class="token string">&quot;Go GC&quot;</span>
				s <span class="token operator">+=</span> <span class="token string">&quot; &quot;</span> <span class="token operator">+</span> <span class="token string">&quot;Hello&quot;</span>
				s <span class="token operator">+=</span> <span class="token string">&quot; &quot;</span> <span class="token operator">+</span> <span class="token string">&quot;World&quot;</span>
				<span class="token boolean">_</span> <span class="token operator">=</span> s
			<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	f<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token string">&quot;trace.out&quot;</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> f<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	trace<span class="token punctuation">.</span><span class="token function">Start</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
	<span class="token keyword">defer</span> trace<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		<span class="token keyword">var</span> t time<span class="token punctuation">.</span>Time
		<span class="token keyword">for</span> atomic<span class="token punctuation">.</span><span class="token function">LoadInt32</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stop<span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token punctuation">{</span>
			t <span class="token operator">=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			runtime<span class="token punctuation">.</span><span class="token function">GC</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			sum <span class="token operator">+=</span> time<span class="token punctuation">.</span><span class="token function">Since</span><span class="token punctuation">(</span>t<span class="token punctuation">)</span>
			count<span class="token operator">++</span>
		<span class="token punctuation">}</span>
		fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;GC spend avg: %v\n&quot;</span><span class="token punctuation">,</span> time<span class="token punctuation">.</span><span class="token function">Duration</span><span class="token punctuation">(</span><span class="token function">int64</span><span class="token punctuation">(</span>sum<span class="token punctuation">)</span><span class="token operator">/</span>count<span class="token punctuation">)</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	atomic<span class="token punctuation">.</span><span class="token function">StoreInt32</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>stop<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这个程序的执行结果是：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ go build -o main
$ ./main
GC spend avg: <span class="token number">2</span>.583421ms
</code></pre></div><p>GC 平均执行一次需要长达 2ms 的时间，我们再进一步观察 trace 的结果：</p> <p><img src="/assets/img/gc-tuning-ex1-1.22b17530.png" alt=""></p> <p>程序的整个执行过程中仅执行了一次 GC，而且仅 Sweep STW 就耗费了超过 1 ms，非常反常。甚至查看赋值器 mutator 的 CPU 利用率，在整个 trace 尺度下连 40% 都不到：</p> <p><img src="/assets/img/gc-tuning-ex1-2.286b99c2.png" alt=""></p> <p>主要原因是什么呢？我们不妨查看 goroutine 的分析：</p> <p><img src="/assets/img/gc-tuning-ex1-3.d92b9432.png" alt=""></p> <p>在这个榜单中我们不难发现，goroutine 的执行时间占其生命周期总时间非常短的一部分，但大部分时间都花费在调度器的等待上了（蓝色的部分），说明同时创建大量 goroutine 对调度器产生的压力确实不小，我们不妨将这一产生速率减慢，一批一批地创建 goroutine：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	wg <span class="token operator">:=</span> sync<span class="token punctuation">.</span>WaitGroup<span class="token punctuation">{</span><span class="token punctuation">}</span>
	<span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> n <span class="token operator">&lt;</span> <span class="token number">100</span><span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
		wg<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span>
		<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">8</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
			<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
				s <span class="token operator">:=</span> <span class="token string">&quot;Go GC&quot;</span>
				s <span class="token operator">+=</span> <span class="token string">&quot; &quot;</span> <span class="token operator">+</span> <span class="token string">&quot;Hello&quot;</span>
				s <span class="token operator">+=</span> <span class="token string">&quot; &quot;</span> <span class="token operator">+</span> <span class="token string">&quot;World&quot;</span>
				<span class="token boolean">_</span> <span class="token operator">=</span> s
				wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
		wg<span class="token punctuation">.</span><span class="token function">Wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这时候我们再来看：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ go build -o main
$ ./main
GC spend avg: <span class="token number">328.54</span>µs
</code></pre></div><p>GC 的平均时间就降到 300 微秒了。这时的赋值器 CPU 使用率也提高到了 60%，相对来说就很可观了：</p> <p><img src="/assets/img/gc-tuning-ex1-4.2cc79d51.png" alt=""></p> <p>当然，这个程序仍然有优化空间，例如我们其实没有必要等待很多 goroutine 同时执行完毕才去执行下一组 goroutine。而可以当一个 goroutine 执行完毕时，直接启动一个新的 goroutine，也就是 goroutine 池的使用。
有兴趣的读者可以沿着这个思路进一步优化这个程序中赋值器对 CPU 的使用率。</p> <h3 id="例2：降低并复用已经申请的内存"><a href="#例2：降低并复用已经申请的内存" class="header-anchor">#</a> 例2：降低并复用已经申请的内存</h3> <p>我们通过一个非常简单的 Web 程序来说明复用内存的重要性。在这个程序中，每当产生一个 <code>/example2</code>
的请求时，都会创建一段内存，并用于进行一些后续的工作。</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;net/http&quot;</span>
	<span class="token boolean">_</span> <span class="token string">&quot;net/http/pprof&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">newBuf</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span> <span class="token punctuation">{</span>
	<span class="token keyword">return</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token operator">&lt;&lt;</span><span class="token number">20</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">&quot;localhost:6060&quot;</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  
	http<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">&quot;/example2&quot;</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		b <span class="token operator">:=</span> <span class="token function">newBuf</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

		<span class="token comment">// 模拟执行一些工作</span>
		<span class="token keyword">for</span> idx <span class="token operator">:=</span> <span class="token keyword">range</span> b <span class="token punctuation">{</span>
			b<span class="token punctuation">[</span>idx<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">1</span>
		<span class="token punctuation">}</span>

		fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">&quot;done, %v&quot;</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>URL<span class="token punctuation">.</span>Path<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span><span class="token punctuation">)</span>
	http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">&quot;:8080&quot;</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>为了进行性能分析，我们还额外创建了一个监听 6060 端口的 goroutine，用于使用 pprof 进行分析。
我们先让服务器跑起来：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ go build -o main
$ ./main
</code></pre></div><p>我们这次使用 pprof 的 trace 来查看 GC 在此服务器中面对大量请求时候的状态，要使用 trace 可以通过访问 <code>/debug/pprof/trace</code> 路由来进行，其中 <code>seconds</code> 参数设置为 20s，并将 trace 的结果保存为 <code>trace.out</code>:</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ <span class="token function">wget</span> http://127.0.0.1:6060/debug/pprof/trace<span class="token punctuation">\</span>?seconds<span class="token punctuation">\</span><span class="token operator">=</span><span class="token number">20</span> -O trace.out
--2020-01-01 <span class="token number">22</span>:13:34--  http://127.0.0.1:6060/debug/pprof/trace?seconds<span class="token operator">=</span><span class="token number">20</span>
Connecting to <span class="token number">127.0</span>.0.1:6060<span class="token punctuation">..</span>. connected.
HTTP request sent, awaiting response<span class="token punctuation">..</span>.
</code></pre></div><p>这时候我们使用一个压测工具 <code>ab</code>，来同时产生 500 个请求
（<code>-n</code> 一共 500 个请求，<code>-c</code> 一个时刻执行请求的数量，每次 100 个并发请求）：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ ab -n <span class="token number">500</span> -c <span class="token number">100</span> http://127.0.0.1:8080/example2
This is ApacheBench, Version <span class="token number">2.3</span> <span class="token operator">&lt;</span><span class="token variable">$Revision</span><span class="token builtin class-name">:</span> <span class="token number">1843412</span> $<span class="token operator">&gt;</span>
Copyright <span class="token number">1996</span> Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking <span class="token number">127.0</span>.0.1 <span class="token punctuation">(</span>be patient<span class="token punctuation">)</span>
Completed <span class="token number">100</span> requests
Completed <span class="token number">200</span> requests
Completed <span class="token number">300</span> requests
Completed <span class="token number">400</span> requests
Completed <span class="token number">500</span> requests
Finished <span class="token number">500</span> requests


Server Software:        
Server Hostname:        <span class="token number">127.0</span>.0.1
Server Port:            <span class="token number">8080</span>

Document Path:          /example2
Document Length:        <span class="token number">14</span> bytes

Concurrency Level:      <span class="token number">100</span>
Time taken <span class="token keyword">for</span> tests:   <span class="token number">0.987</span> seconds
Complete requests:      <span class="token number">500</span>
Failed requests:        <span class="token number">0</span>
Total transferred:      <span class="token number">65500</span> bytes
HTML transferred:       <span class="token number">7000</span> bytes
Requests per second:    <span class="token number">506.63</span> <span class="token punctuation">[</span><span class="token comment">#/sec] (mean)</span>
Time per request:       <span class="token number">197.382</span> <span class="token punctuation">[</span>ms<span class="token punctuation">]</span> <span class="token punctuation">(</span>mean<span class="token punctuation">)</span>
Time per request:       <span class="token number">1.974</span> <span class="token punctuation">[</span>ms<span class="token punctuation">]</span> <span class="token punctuation">(</span>mean, across all concurrent requests<span class="token punctuation">)</span>
Transfer rate:          <span class="token number">64.81</span> <span class="token punctuation">[</span>Kbytes/sec<span class="token punctuation">]</span> received

Connection Times <span class="token punctuation">(</span>ms<span class="token punctuation">)</span>
              min  mean<span class="token punctuation">[</span>+/-sd<span class="token punctuation">]</span> median   max
Connect:        <span class="token number">0</span>    <span class="token number">1</span>   <span class="token number">1.1</span>      <span class="token number">0</span>       <span class="token number">7</span>
Processing:    <span class="token number">13</span>  <span class="token number">179</span>  <span class="token number">77.5</span>    <span class="token number">170</span>     <span class="token number">456</span>
Waiting:       <span class="token number">10</span>  <span class="token number">168</span>  <span class="token number">78.8</span>    <span class="token number">162</span>     <span class="token number">455</span>
Total:         <span class="token number">14</span>  <span class="token number">180</span>  <span class="token number">77.3</span>    <span class="token number">171</span>     <span class="token number">458</span>

Percentage of the requests served within a certain <span class="token function">time</span> <span class="token punctuation">(</span>ms<span class="token punctuation">)</span>
  <span class="token number">50</span>%    <span class="token number">171</span>
  <span class="token number">66</span>%    <span class="token number">203</span>
  <span class="token number">75</span>%    <span class="token number">222</span>
  <span class="token number">80</span>%    <span class="token number">239</span>
  <span class="token number">90</span>%    <span class="token number">281</span>
  <span class="token number">95</span>%    <span class="token number">335</span>
  <span class="token number">98</span>%    <span class="token number">365</span>
  <span class="token number">99</span>%    <span class="token number">400</span>
 <span class="token number">100</span>%    <span class="token number">458</span> <span class="token punctuation">(</span>longest request<span class="token punctuation">)</span>
</code></pre></div><p><img src="/assets/img/gc-tuning-ex2-1.eb934107.png" alt=""></p> <p>GC 反复被触发，一个显而易见的原因就是内存分配过多。我们可以通过 <code>go tool pprof</code> 来查看究竟是谁分配了大量内存（使用 web 指令来使用浏览器打开统计信息的可视化图形）：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ go tool pprof http://127.0.0.1:6060/debug/pprof/heap
Fetching profile over HTTP from http://localhost:6060/debug/pprof/heap
Saved profile <span class="token keyword">in</span> /Users/changkun/pprof/pprof.alloc_objects.alloc_space.inuse_o
bjects.inuse_space.003.pb.gz
Type: inuse_space
Time: Jan <span class="token number">1</span>, <span class="token number">2020</span> at <span class="token number">11</span>:15pm <span class="token punctuation">(</span>CET<span class="token punctuation">)</span>
Entering interactive mode <span class="token punctuation">(</span>type <span class="token string">&quot;help&quot;</span> <span class="token keyword">for</span> commands, <span class="token string">&quot;o&quot;</span> <span class="token keyword">for</span> options<span class="token punctuation">)</span>
<span class="token punctuation">(</span>pprof<span class="token punctuation">)</span> web
<span class="token punctuation">(</span>pprof<span class="token punctuation">)</span> 
</code></pre></div><p><img src="/assets/img/gc-tuning-ex2-2.5129ba7e.png" alt=""></p> <p>可见 <code>newBuf</code> 产生的申请的内存过多，现在我们使用 sync.Pool 来复用 <code>newBuf</code> 所产生的对象：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;net/http&quot;</span>
	<span class="token boolean">_</span> <span class="token string">&quot;net/http/pprof&quot;</span>
	<span class="token string">&quot;sync&quot;</span>
<span class="token punctuation">)</span>

<span class="token comment">// 使用 sync.Pool 复用需要的 buf</span>
<span class="token keyword">var</span> bufPool <span class="token operator">=</span> sync<span class="token punctuation">.</span>Pool<span class="token punctuation">{</span>
	New<span class="token punctuation">:</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span> <span class="token punctuation">{</span>
		<span class="token keyword">return</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token operator">&lt;&lt;</span><span class="token number">20</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
		http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">&quot;localhost:6060&quot;</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	http<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">&quot;/example2&quot;</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">{</span>
		b <span class="token operator">:=</span> bufPool<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">)</span>
		<span class="token keyword">for</span> idx <span class="token operator">:=</span> <span class="token keyword">range</span> b <span class="token punctuation">{</span>
			b<span class="token punctuation">[</span>idx<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span>
		<span class="token punctuation">}</span>
		fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">&quot;done, %v&quot;</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>URL<span class="token punctuation">.</span>Path<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
		bufPool<span class="token punctuation">.</span><span class="token function">Put</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span>
	<span class="token punctuation">}</span><span class="token punctuation">)</span>
	http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">&quot;:8080&quot;</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
</code></pre></div><p>其中 ab 输出的统计结果为：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ ab -n <span class="token number">500</span> -c <span class="token number">100</span> http://127.0.0.1:8080/example2
This is ApacheBench, Version <span class="token number">2.3</span> <span class="token operator">&lt;</span><span class="token variable">$Revision</span><span class="token builtin class-name">:</span> <span class="token number">1843412</span> $<span class="token operator">&gt;</span>
Copyright <span class="token number">1996</span> Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking <span class="token number">127.0</span>.0.1 <span class="token punctuation">(</span>be patient<span class="token punctuation">)</span>
Completed <span class="token number">100</span> requests
Completed <span class="token number">200</span> requests
Completed <span class="token number">300</span> requests
Completed <span class="token number">400</span> requests
Completed <span class="token number">500</span> requests
Finished <span class="token number">500</span> requests


Server Software:        
Server Hostname:        <span class="token number">127.0</span>.0.1
Server Port:            <span class="token number">8080</span>

Document Path:          /example2
Document Length:        <span class="token number">14</span> bytes

Concurrency Level:      <span class="token number">100</span>
Time taken <span class="token keyword">for</span> tests:   <span class="token number">0.427</span> seconds
Complete requests:      <span class="token number">500</span>
Failed requests:        <span class="token number">0</span>
Total transferred:      <span class="token number">65500</span> bytes
HTML transferred:       <span class="token number">7000</span> bytes
Requests per second:    <span class="token number">1171.32</span> <span class="token punctuation">[</span><span class="token comment">#/sec] (mean)</span>
Time per request:       <span class="token number">85.374</span> <span class="token punctuation">[</span>ms<span class="token punctuation">]</span> <span class="token punctuation">(</span>mean<span class="token punctuation">)</span>
Time per request:       <span class="token number">0.854</span> <span class="token punctuation">[</span>ms<span class="token punctuation">]</span> <span class="token punctuation">(</span>mean, across all concurrent requests<span class="token punctuation">)</span>
Transfer rate:          <span class="token number">149.85</span> <span class="token punctuation">[</span>Kbytes/sec<span class="token punctuation">]</span> received

Connection Times <span class="token punctuation">(</span>ms<span class="token punctuation">)</span>
              min  mean<span class="token punctuation">[</span>+/-sd<span class="token punctuation">]</span> median   max
Connect:        <span class="token number">0</span>    <span class="token number">1</span>   <span class="token number">1.4</span>      <span class="token number">1</span>       <span class="token number">9</span>
Processing:     <span class="token number">5</span>   <span class="token number">75</span>  <span class="token number">48.2</span>     <span class="token number">66</span>     <span class="token number">211</span>
Waiting:        <span class="token number">5</span>   <span class="token number">72</span>  <span class="token number">46.8</span>     <span class="token number">63</span>     <span class="token number">207</span>
Total:          <span class="token number">5</span>   <span class="token number">77</span>  <span class="token number">48.2</span>     <span class="token number">67</span>     <span class="token number">211</span>

Percentage of the requests served within a certain <span class="token function">time</span> <span class="token punctuation">(</span>ms<span class="token punctuation">)</span>
  <span class="token number">50</span>%     <span class="token number">67</span>
  <span class="token number">66</span>%     <span class="token number">89</span>
  <span class="token number">75</span>%    <span class="token number">107</span>
  <span class="token number">80</span>%    <span class="token number">122</span>
  <span class="token number">90</span>%    <span class="token number">148</span>
  <span class="token number">95</span>%    <span class="token number">167</span>
  <span class="token number">98</span>%    <span class="token number">196</span>
  <span class="token number">99</span>%    <span class="token number">204</span>
 <span class="token number">100</span>%    <span class="token number">211</span> <span class="token punctuation">(</span>longest request<span class="token punctuation">)</span>
</code></pre></div><p>但从 <code>Requests per second</code> 每秒请求数来看，从原来的 506.63 变为 1171.32 得到了近乎一倍的提升。从 trace 的结果来看，GC 也没有频繁的被触发从而长期消耗 CPU 使用率：</p> <p><img src="/assets/img/gc-tuning-ex2-3.7165b1f8.png" alt=""></p> <p>sync.Pool 是内存复用的一个最为显著的例子，从语言层面上还有很多类似的例子，例如在例 1 中，<code>concat</code> 函数可以预先分配一定长度的缓存，而后再通过 append 的方式将字符串存储到缓存中：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">concat</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	wg <span class="token operator">:=</span> sync<span class="token punctuation">.</span>WaitGroup<span class="token punctuation">{</span><span class="token punctuation">}</span>
	<span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> n <span class="token operator">&lt;</span> <span class="token number">100</span><span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
		wg<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span><span class="token number">8</span><span class="token punctuation">)</span>
		<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">8</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
			<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
				s <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span>
				s <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">&quot;Go GC&quot;</span><span class="token operator">...</span><span class="token punctuation">)</span>
				s <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">' '</span><span class="token punctuation">)</span>
				s <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">&quot;Hello&quot;</span><span class="token operator">...</span><span class="token punctuation">)</span>
				s <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">' '</span><span class="token punctuation">)</span>
				s <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> <span class="token string">&quot;World&quot;</span><span class="token operator">...</span><span class="token punctuation">)</span>
				<span class="token boolean">_</span> <span class="token operator">=</span> <span class="token function">string</span><span class="token punctuation">(</span>s<span class="token punctuation">)</span>
				wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		<span class="token punctuation">}</span>
		wg<span class="token punctuation">.</span><span class="token function">Wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>原因在于 <code>+</code> 运算符会随着字符串长度的增加而申请更多的内存，并将内容从原来的内存位置拷贝到新的内存位置，造成大量不必要的内存分配，先提前分配好足够的内存，再慢慢地填充，也是一种减少内存分配、复用内存形式的一种表现。</p> <h3 id="例3：调整-gogc"><a href="#例3：调整-gogc" class="header-anchor">#</a> 例3：调整 GOGC</h3> <p>我们已经知道了 GC 的触发原则是由步调算法来控制的，其关键在于估计下一次需要触发 GC 时，堆的大小。可想而知，如果我们在遇到海量请求的时，为了避免 GC 频繁触发，是否可以通过将 GOGC 的值设置得更大，让 GC 触发的时间变得更晚，从而减少其触发频率，进而增加用户代码对机器的使用率呢？答案是肯定的。</p> <p>我们可以非常简单粗暴的将 GOGC 调整为 1000，来执行上一个例子中未复用对象之前的程序：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ <span class="token assign-left variable">GOGC</span><span class="token operator">=</span><span class="token number">1000</span> ./main
</code></pre></div><p>这时我们再重新执行压测：</p> <div class="language-bash extra-class"><pre class="language-bash"><code>$ ab -n <span class="token number">500</span> -c <span class="token number">100</span> http://127.0.0.1:8080/example2
This is ApacheBench, Version <span class="token number">2.3</span> <span class="token operator">&lt;</span><span class="token variable">$Revision</span><span class="token builtin class-name">:</span> <span class="token number">1843412</span> $<span class="token operator">&gt;</span>
Copyright <span class="token number">1996</span> Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking <span class="token number">127.0</span>.0.1 <span class="token punctuation">(</span>be patient<span class="token punctuation">)</span>
Completed <span class="token number">100</span> requests
Completed <span class="token number">200</span> requests
Completed <span class="token number">300</span> requests
Completed <span class="token number">400</span> requests
Completed <span class="token number">500</span> requests
Finished <span class="token number">500</span> requests


Server Software:        
Server Hostname:        <span class="token number">127.0</span>.0.1
Server Port:            <span class="token number">8080</span>

Document Path:          /example2
Document Length:        <span class="token number">14</span> bytes

Concurrency Level:      <span class="token number">100</span>
Time taken <span class="token keyword">for</span> tests:   <span class="token number">0.923</span> seconds
Complete requests:      <span class="token number">500</span>
Failed requests:        <span class="token number">0</span>
Total transferred:      <span class="token number">65500</span> bytes
HTML transferred:       <span class="token number">7000</span> bytes
Requests per second:    <span class="token number">541.61</span> <span class="token punctuation">[</span><span class="token comment">#/sec] (mean)</span>
Time per request:       <span class="token number">184.636</span> <span class="token punctuation">[</span>ms<span class="token punctuation">]</span> <span class="token punctuation">(</span>mean<span class="token punctuation">)</span>
Time per request:       <span class="token number">1.846</span> <span class="token punctuation">[</span>ms<span class="token punctuation">]</span> <span class="token punctuation">(</span>mean, across all concurrent requests<span class="token punctuation">)</span>
Transfer rate:          <span class="token number">69.29</span> <span class="token punctuation">[</span>Kbytes/sec<span class="token punctuation">]</span> received

Connection Times <span class="token punctuation">(</span>ms<span class="token punctuation">)</span>
              min  mean<span class="token punctuation">[</span>+/-sd<span class="token punctuation">]</span> median   max
Connect:        <span class="token number">0</span>    <span class="token number">1</span>   <span class="token number">1.8</span>      <span class="token number">0</span>      <span class="token number">20</span>
Processing:     <span class="token number">9</span>  <span class="token number">171</span> <span class="token number">210.4</span>     <span class="token number">66</span>     <span class="token number">859</span>
Waiting:        <span class="token number">5</span>  <span class="token number">158</span> <span class="token number">199.6</span>     <span class="token number">62</span>     <span class="token number">813</span>
Total:          <span class="token number">9</span>  <span class="token number">173</span> <span class="token number">210.6</span>     <span class="token number">68</span>     <span class="token number">860</span>

Percentage of the requests served within a certain <span class="token function">time</span> <span class="token punctuation">(</span>ms<span class="token punctuation">)</span>
  <span class="token number">50</span>%     <span class="token number">68</span>
  <span class="token number">66</span>%    <span class="token number">133</span>
  <span class="token number">75</span>%    <span class="token number">198</span>
  <span class="token number">80</span>%    <span class="token number">292</span>
  <span class="token number">90</span>%    <span class="token number">566</span>
  <span class="token number">95</span>%    <span class="token number">696</span>
  <span class="token number">98</span>%    <span class="token number">723</span>
  <span class="token number">99</span>%    <span class="token number">743</span>
 <span class="token number">100</span>%    <span class="token number">860</span> <span class="token punctuation">(</span>longest request<span class="token punctuation">)</span>
</code></pre></div><p>可以看到，压测的结果得到了一定幅度的改善（<code>Requests per second</code> 从原来的 506.63 提高为了 541.61），
并且 GC 的执行频率明显降低：</p> <p><img src="/assets/img/gc-tuning-ex3.121f1ea2.png" alt=""></p> <p>在实际实践中可表现为需要紧急处理一些由 GC 带来的瓶颈时，人为将 GOGC 调大，加钱加内存，扛过这一段峰值流量时期。</p> <p>当然，这种做法其实是治标不治本，并没有从根本上解决内存分配过于频繁的问题，极端情况下，反而会由于 GOGC 太大而导致回收不及时而耗费更多的时间来清理产生的垃圾，这对时间不算敏感的应用还好，但对实时性要求较高的程序来说就是致命的打击了。</p> <p>因此这时更妥当的做法仍然是，定位问题的所在，并从代码层面上进行优化。</p> <h3 id="小结"><a href="#小结" class="header-anchor">#</a> 小结</h3> <p>通过上面的三个例子我们可以看到在 GC 调优过程中 <code>go tool pprof</code> 和 <code>go tool trace</code> 的强大作用是帮助我们快速定位 GC 导致瓶颈的具体位置，但这些例子中仅仅覆盖了其功能的很小一部分，我们也没有必要完整覆盖所有的功能，因为总是可以通过<a href="https://golang.org/pkg/net/http/pprof/" target="_blank" rel="noopener noreferrer">http pprof 官方文档<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>、<a href="https://golang.org/pkg/runtime/pprof/" target="_blank" rel="noopener noreferrer">runtime pprof官方文档<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>以及<a href="https://golang.org/pkg/runtime/trace/" target="_blank" rel="noopener noreferrer">trace 官方文档<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>来举一反三。</p> <p>现在我们来总结一下前面三个例子中的优化情况：</p> <ol><li>控制内存分配的速度，限制 goroutine 的数量，从而提高赋值器对 CPU 的利用率。</li> <li>减少并复用内存，例如使用 sync.Pool 来复用需要频繁创建临时对象，例如提前分配足够的内存来降低多余的拷贝。</li> <li>需要时，增大 GOGC 的值，降低 GC 的运行频率。</li></ol> <p>这三种情况几乎涵盖了 GC 调优中的核心思路，虽然从语言上还有很多小技巧可说，但我们并不会在这里事无巨细的进行总结。实际情况也是千变万化，我们更应该着重于培养具体问题具体分析的能力。</p> <p>当然，我们还应该谨记 <strong>过早优化是万恶之源</strong>这一警语，在没有遇到应用的真正瓶颈时，将宝贵的时间分配在开发中其他优先级更高的任务上。</p> <h2 id="_15-go-的垃圾回收器有哪些相关的-api？其作用分别是什么？"><a href="#_15-go-的垃圾回收器有哪些相关的-api？其作用分别是什么？" class="header-anchor">#</a> 15. Go 的垃圾回收器有哪些相关的 API？其作用分别是什么？</h2> <p>在 Go 中存在数量极少的与 GC 相关的 API，它们是</p> <ul><li>runtime.GC：手动触发 GC</li> <li>runtime.ReadMemStats：读取内存相关的统计信息，其中包含部分 GC 相关的统计信息</li> <li>debug.FreeOSMemory：手动将内存归还给操作系统</li> <li>debug.ReadGCStats：读取关于 GC 的相关统计信息</li> <li>debug.SetGCPercent：设置 GOGC 调步变量</li> <li>debug.SetMaxHeap（尚未发布）：设置 Go 程序堆的上限值
</li></ul> <h1 id="gc-的历史及演进"><a href="#gc-的历史及演进" class="header-anchor">#</a> GC 的历史及演进</h1> <h2 id="_16-go-历史各个版本在-gc-方面的改进？"><a href="#_16-go-历史各个版本在-gc-方面的改进？" class="header-anchor">#</a> 16. Go 历史各个版本在 GC 方面的改进？</h2> <ul><li><p>Go 1：串行三色标记清扫</p></li> <li><p>Go 1.3：并行清扫，标记过程需要 STW，停顿时间在约几百毫秒</p></li> <li><p>Go 1.5：并发标记清扫，停顿时间在一百毫秒以内</p></li> <li><p>Go 1.6：使用 bitmap 来记录回收内存的位置，大幅优化垃圾回收器自身消耗的内存，停顿时间在十毫秒以内</p></li> <li><p>Go 1.7：停顿时间控制在两毫秒以内</p></li> <li><p>Go 1.8：混合写屏障，停顿时间在半个毫秒左右</p></li> <li><p>Go 1.9：彻底移除了栈的重扫描过程</p></li> <li><p>Go 1.12：整合了两个阶段的 Mark Termination，但引入了一个严重的 GC Bug 至今未修（见问题 20），尚无该 Bug 对 GC 性能影响的报告</p></li> <li><p>Go 1.13：着手解决向操作系统归还内存的，提出了新的 Scavenger</p></li> <li><p>Go 1.14：替代了仅存活了一个版本的 scavenger，全新的页分配器，优化分配内存过程的速率与现有的扩展性问题，并引入了异步抢占，解决了由于密集循环导致的 STW 时间过长的问题</p></li></ul> <p>可以用下图直观地说明 GC 的演进历史：</p> <p><img src="assets/gc1.png" alt=""></p> <p>在 Go 1 刚发布时的版本中，甚至没有将 Mark-Sweep 的过程并行化，当需要进行垃圾回收时，所有的代码都必须进入 STW 的状态。而到了 Go 1.1 时，官方迅速地将清扫过程进行了并行化的处理，即仅在标记阶段进入 STW。</p> <p>这一想法很自然，因为并行化导致算法结果不一致的情况仅仅发生在标记阶段，而当时的垃圾回收器没有针对并行结果的一致性进行任何优化，因此才需要在标记阶段进入 STW。对于 Scavenger 而言，早期的版本中会有一个单独的线程来定期将多余的内存归还给操作系统。</p> <p><img src="assets/gc2.png" alt=""></p> <p>而到了 Go 1.5 后，Go 团队花费了相当大的力气，通过引入写屏障的机制来保证算法的一致性，才得以将整个 GC 控制在很小的 STW 内，而到了 1.8 时，由于新的混合屏障的出现，消除了对栈本身的重新扫描，STW 的时间进一步缩减。</p> <p>从这个时候开始，Scavenger 已经从独立线程中移除，并合并至系统监控这个独立的线程中，并周期性地向操作系统归还内存，但仍然会有内存溢出这种比较极端的情况出现，因为程序可能在短时间内应对突发性的内存申请需求时，内存还没来得及归还操作系统，导致堆不断向操作系统申请内存，从而出现内存溢出。</p> <p><img src="assets/gc3.png" alt=""></p> <p>到了 Go 1.13，定期归还操作系统的问题得以解决，Go 团队开始将周期性的 Scavenger 转化为可被调度的 goroutine，并将其与用户代码并发执行。而到了 Go 1.14，这一向操作系统归还内存的操作时间进一步得到缩减。</p> <h2 id="_17-go-gc-在演化过程中还存在哪些其他设计？为什么没有被采用？"><a href="#_17-go-gc-在演化过程中还存在哪些其他设计？为什么没有被采用？" class="header-anchor">#</a> 17. Go GC 在演化过程中还存在哪些其他设计？为什么没有被采用？</h2> <h3 id="并发栈重扫"><a href="#并发栈重扫" class="header-anchor">#</a> 并发栈重扫</h3> <p>正如我们前面所说，允许灰色赋值器存在的垃圾回收器需要引入重扫过程来保证算法的正确性，除了引入混合屏障来消除重扫这一过程外，有另一种做法可以提高重扫过程的性能，那就是将重扫的过程并发执行。然而这一<a href="https://github.com/golang/proposal/blob/master/design/17505-concurrent-rescan.md" target="_blank" rel="noopener noreferrer">方案<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>并没有得以实现，原因很简单：实现过程相比引入混合屏障而言十分复杂，而且引入混合屏障能够消除重扫这一过程，将简化垃圾回收的步骤。</p> <h3 id="roc"><a href="#roc" class="header-anchor">#</a> ROC</h3> <p>ROC 的全称是<a href="https://docs.google.com/document/d/1gCsFxXamW8RRvOe5hECz98Ftk-tcRRJcDFANj2VwCB0/edit" target="_blank" rel="noopener noreferrer">面向请求的回收器<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>（Request Oriented Collector），它其实也是分代 GC 的一种重新叙述。它提出了一个请求假设（Request Hypothesis）：与一个完整请求、休眠 goroutine 所关联的对象比其他对象更容易死亡。这个假设听起来非常符合直觉，但在实现上，由于垃圾回收器必须确保是否有 goroutine 私有指针被写入公共对象，因此写屏障必须一直打开，这也就产生了该方法的致命缺点：昂贵的写屏障及其带来的缓存未命中，这也是这一设计最终没有被采用的主要原因。</p> <h3 id="传统分代-gc"><a href="#传统分代-gc" class="header-anchor">#</a> 传统分代 GC</h3> <p>在发现 ROC 性能不行之后，作为备选方案，Go 团队还尝试了实现<a href="https://go-review.googlesource.com/c/go/+/137476/12" target="_blank" rel="noopener noreferrer">传统的分代式 GC<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>。但最终同样发现分代假设并不适用于 Go 的运行栈机制，年轻代对象在栈上就已经死亡，扫描本就该回收的执行栈并没有为由于分代假设带来明显的性能提升。这也是这一设计最终没有被采用的主要原因。</p> <h2 id="_18-目前提供-gc-的语言以及不提供-gc-的语言有哪些？gc-和-no-gc-各自的优缺点是什么？"><a href="#_18-目前提供-gc-的语言以及不提供-gc-的语言有哪些？gc-和-no-gc-各自的优缺点是什么？" class="header-anchor">#</a> 18. 目前提供 GC 的语言以及不提供 GC 的语言有哪些？GC 和 No GC 各自的优缺点是什么？</h2> <p>从原理上而言，所有的语言都能够自行实现 GC。从语言诞生之初就提供 GC 的语言，例如：</p> <ul><li>Python</li> <li>JavaScript</li> <li>Java</li> <li>Objective-C</li> <li>Swift</li></ul> <p>而不以 GC 为目标，被直接设计为手动管理内存、但可以自行实现 GC 的语言有：</p> <ul><li>C</li> <li>C++</li></ul> <p>也有一些语言可以在编译期，依靠编译器插入清理代码的方式，实现精准的清理，例如：</p> <ul><li>Rust</li></ul> <p>垃圾回收使程序员无需手动处理内存释放，从而能够消除一些需要手动管理内存才会出现的运行时错误：</p> <ol><li>在仍然有指向内存区块的指针的情况下释放这块内存时，会产生悬挂指针，从而后续可能错误的访问已经用于他用的内存区域。</li> <li>多重释放同一块申请的内存区域可能导致不可知的内存损坏。</li></ol> <p>当然，垃圾回收也会伴随一些缺陷，这也就造就了没有 GC 的一些优势：</p> <ol><li>没有额外的性能开销</li> <li>精准的手动内存管理，极致的利用机器的性能</li></ol> <h2 id="_19-go-对比-java、v8-中-javascript-的-gc-性能如何？"><a href="#_19-go-对比-java、v8-中-javascript-的-gc-性能如何？" class="header-anchor">#</a> 19. Go 对比 Java、V8 中 JavaScript 的 GC 性能如何？</h2> <p>无论是 Java 还是 JavaScript 中的 GC 均为分代式 GC。分代式 GC 的一个核心假设就是分代假说：将对象依据存活时间分配到不同的区域，每次回收只回收其中的一个区域。</p> <h3 id="v8-的-gc"><a href="#v8-的-gc" class="header-anchor">#</a> V8 的 GC</h3> <p>在 V8 中主要将内存分为新生代和老生代。新生代中的对象为存活时间较短的对象，老生代中的对象为存活时间较长、常驻内存、占用内存较大的对象：</p> <ol><li>新生代中的对象主要通过副垃圾回收器进行回收。该回收过程是一种采用复制的方式实现的垃圾回收算法，它将堆内存一分为二，这两个空间中只有一个处于使用中，另一个则处于闲置状态。处于使用状态的空间称为 From 空间，处于闲置的空间称为 To 空间。分配对象时，先是在 From 空间中进行分配，当开始垃圾回收时，会检查 From 空间中的存活对象，并将这些存活对象复制到 To 空间中，而非存活对象占用的空间被释放。完成复制后，From 空间和 To 空间的角色互换。也就是通过将存活对象在两个空间中进行复制。</li> <li>老生代则由主垃圾回收器负责。它实现的是标记清扫过程，但略有不同之处在于它还会在清扫完成后对内存碎片进行整理，进而是一种标记整理的回收器。</li></ol> <h3 id="java-的-gc"><a href="#java-的-gc" class="header-anchor">#</a> Java 的 GC</h3> <p>Java 的 GC 称之为 G1，并将整个堆分为年轻代、老年代和永久代。包括四种不同的收集操作，从上往下的这几个阶段会选择性地执行，触发条件是用户的配置和实际代码行为的预测。</p> <ol><li>年轻代收集周期：只对年轻代对象进行收集与清理</li> <li>老年代收集周期：只对老年代对象进行收集与清理</li> <li>混合式收集周期：同时对年轻代和老年代进行收集与清理</li> <li>完整 GC 周期：完整的对整个堆进行收集与清理</li></ol> <p>在回收过程中，G1 会对停顿时间进行预测，竭尽所能地调整 GC 的策略从而达到用户代码通过系统参数（<code>-XX:MaxGCPauseMillis</code>）所配置的对停顿时间的要求。</p> <p>这四个周期的执行成本逐渐上升，优化得当的程序可以完全避免完整 GC 周期。</p> <h3 id="性能比较"><a href="#性能比较" class="header-anchor">#</a> 性能比较</h3> <p>在 Go、Java 和 V8 JavaScript 之间比较 GC 的性能本质上是一个不切实际的问题。如前面所说，垃圾回收器的设计权衡了很多方面的因素，同时还受语言自身设计的影响，因为语言的设计也直接影响了程序员编写代码的形式，也就自然影响了产生垃圾的方式。</p> <p>但总的来说，他们三者对垃圾回收的实现都需要 STW，并均已达到了用户代码几乎无法感知到的状态（据 Go GC 作者 Austin 宣称 <a href="https://groups.google.com/d/msg/golang-dev/Ab1sFeoZg_8/_DaL0E8fAwAJ" target="_blank" rel="noopener noreferrer">STW 小于 100 微秒<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>）。当然，随着 STW 的减少，垃圾回收器会增加 CPU 的使用率，这也是程序员在编写代码时需要手动进行优化的部分，即充分考虑内存分配的必要性，减少过多申请内存带给垃圾回收器的压力。</p> <h2 id="_20-目前-go-语言的-gc-还存在哪些问题？"><a href="#_20-目前-go-语言的-gc-还存在哪些问题？" class="header-anchor">#</a> 20. 目前 Go 语言的 GC 还存在哪些问题？</h2> <p>尽管 Go 团队宣称 STW 停顿时间得以优化到 100 微秒级别，但这本质上是一种取舍。原本的 STW 某种意义上来说其实转移到了可能导致用户代码停顿的几个位置；除此之外，由于运行时调度器的实现方式，同样对 GC 存在一定程度的影响。</p> <p>目前 Go 中的 GC 仍然存在以下问题：</p> <h3 id="_1-mark-assist-停顿时间过长"><a href="#_1-mark-assist-停顿时间过长" class="header-anchor">#</a> 1. Mark Assist 停顿时间过长</h3> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
	<span class="token string">&quot;fmt&quot;</span>
	<span class="token string">&quot;os&quot;</span>
	<span class="token string">&quot;runtime&quot;</span>
	<span class="token string">&quot;runtime/trace&quot;</span>
	<span class="token string">&quot;time&quot;</span>
<span class="token punctuation">)</span>

<span class="token keyword">const</span> <span class="token punctuation">(</span>
	windowSize <span class="token operator">=</span> <span class="token number">200000</span>
	msgCount   <span class="token operator">=</span> <span class="token number">1000000</span>
<span class="token punctuation">)</span>

<span class="token keyword">var</span> <span class="token punctuation">(</span>
	best    time<span class="token punctuation">.</span>Duration <span class="token operator">=</span> time<span class="token punctuation">.</span>Second
	bestAt  time<span class="token punctuation">.</span>Time
	worst   time<span class="token punctuation">.</span>Duration
	worstAt time<span class="token punctuation">.</span>Time

	start <span class="token operator">=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	f<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">:=</span> os<span class="token punctuation">.</span><span class="token function">Create</span><span class="token punctuation">(</span><span class="token string">&quot;trace.out&quot;</span><span class="token punctuation">)</span>
	<span class="token keyword">defer</span> f<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	trace<span class="token punctuation">.</span><span class="token function">Start</span><span class="token punctuation">(</span>f<span class="token punctuation">)</span>
	<span class="token keyword">defer</span> trace<span class="token punctuation">.</span><span class="token function">Stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">5</span><span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		<span class="token function">measure</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
		worst <span class="token operator">=</span> <span class="token number">0</span>
		best <span class="token operator">=</span> time<span class="token punctuation">.</span>Second
		runtime<span class="token punctuation">.</span><span class="token function">GC</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">measure</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	<span class="token keyword">var</span> c channel
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> msgCount<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
		c<span class="token punctuation">.</span><span class="token function">sendMsg</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	fmt<span class="token punctuation">.</span><span class="token function">Printf</span><span class="token punctuation">(</span><span class="token string">&quot;Best send delay %v at %v, worst send delay: %v at %v. Wall clock: %v \n&quot;</span><span class="token punctuation">,</span> best<span class="token punctuation">,</span> bestAt<span class="token punctuation">.</span><span class="token function">Sub</span><span class="token punctuation">(</span>start<span class="token punctuation">)</span><span class="token punctuation">,</span> worst<span class="token punctuation">,</span> worstAt<span class="token punctuation">.</span><span class="token function">Sub</span><span class="token punctuation">(</span>start<span class="token punctuation">)</span><span class="token punctuation">,</span> time<span class="token punctuation">.</span><span class="token function">Since</span><span class="token punctuation">(</span>start<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">type</span> channel <span class="token punctuation">[</span>windowSize<span class="token punctuation">]</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span>

<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>channel<span class="token punctuation">)</span> <span class="token function">sendMsg</span><span class="token punctuation">(</span>id <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
	start <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	<span class="token comment">// 模拟发送</span>
	<span class="token punctuation">(</span><span class="token operator">*</span>c<span class="token punctuation">)</span><span class="token punctuation">[</span>id<span class="token operator">%</span>windowSize<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">newMsg</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span>

	end <span class="token operator">:=</span> time<span class="token punctuation">.</span><span class="token function">Now</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
	elapsed <span class="token operator">:=</span> end<span class="token punctuation">.</span><span class="token function">Sub</span><span class="token punctuation">(</span>start<span class="token punctuation">)</span>
	<span class="token keyword">if</span> elapsed <span class="token operator">&gt;</span> worst <span class="token punctuation">{</span>
		worst <span class="token operator">=</span> elapsed
		worstAt <span class="token operator">=</span> end
	<span class="token punctuation">}</span>
	<span class="token keyword">if</span> elapsed <span class="token operator">&lt;</span> best <span class="token punctuation">{</span>
		best <span class="token operator">=</span> elapsed
		bestAt <span class="token operator">=</span> end
	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">newMsg</span><span class="token punctuation">(</span>n <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span> <span class="token punctuation">{</span>
	m <span class="token operator">:=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">byte</span><span class="token punctuation">,</span> <span class="token number">1024</span><span class="token punctuation">)</span>
	<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token keyword">range</span> m <span class="token punctuation">{</span>
		m<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">byte</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span>
	<span class="token punctuation">}</span>
	<span class="token keyword">return</span> m
<span class="token punctuation">}</span>
</code></pre></div><p>运行此程序我们可以得到类似下面的结果：</p> <div class="language- extra-class"><pre class="language-text"><code>$ go run main.go

Best send delay 330ns at 773.037956ms, worst send delay: 7.127915ms at 579.835487ms. Wall clock: 831.066632ms 
Best send delay 331ns at 873.672966ms, worst send delay: 6.731947ms at 1.023969626s. Wall clock: 1.515295559s 
Best send delay 330ns at 1.812141567s, worst send delay: 5.34028ms at 2.193858359s. Wall clock: 2.199921749s 
Best send delay 338ns at 2.722161771s, worst send delay: 7.479482ms at 2.665355216s. Wall clock: 2.920174197s 
Best send delay 337ns at 3.173649445s, worst send delay: 6.989577ms at 3.361716121s. Wall clock: 3.615079348s 
</code></pre></div><p><img src="/assets/img/gc-mark-assist.8c38239b.png" alt=""></p> <p>在这个结果中，第一次的最坏延迟时间高达 7.12 毫秒，发生在程序运行 578 毫秒左右。通过 <code>go tool trace</code> 可以发现，这个时间段中，Mark Assist 执行了 7112312ns，约为 7.127915ms；可见，此时最坏情况下，标记辅助拖慢了用户代码的执行，是造成 7 毫秒延迟的原因。</p> <h3 id="_2-sweep-停顿时间过长"><a href="#_2-sweep-停顿时间过长" class="header-anchor">#</a> 2. Sweep 停顿时间过长</h3> <p>同样还是刚才的例子，如果我们仔细观察 Mark Assist 后发生的 Sweep 阶段，竟然对用户代码的影响长达约 30ms，根据调用栈信息可以看到，该 Sweep 过程发生在内存分配阶段：</p> <p><img src="/assets/img/gc-mark-sweep.f2634c0e.png" alt=""></p> <h3 id="_3-由于-gc-算法的不正确性导致-gc-周期被迫重新执行"><a href="#_3-由于-gc-算法的不正确性导致-gc-周期被迫重新执行" class="header-anchor">#</a> 3. 由于 GC 算法的不正确性导致 GC 周期被迫重新执行</h3> <p>此问题很难复现，但是一个已知的问题，根据 Go 团队的描述，<a href="https://github.com/golang/go/issues/27993#issuecomment-441719687" target="_blank" rel="noopener noreferrer">能够在 1334 次构建中发生一次<svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a>，我们可以计算出其触发概率约为 0.0007496251874。虽然发生概率很低，但一旦发生，GC 需要被重新执行，非常不幸。</p> <h3 id="_4-创建大量-goroutine-后导致-gc-消耗更多的-cpu"><a href="#_4-创建大量-goroutine-后导致-gc-消耗更多的-cpu" class="header-anchor">#</a> 4. 创建大量 Goroutine 后导致 GC 消耗更多的 CPU</h3> <p>这个问题可以通过以下程序进行验证：</p> <div class="language-go extra-class"><pre class="language-go"><code><span class="token keyword">func</span> <span class="token function">BenchmarkGCLargeGs</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
	wg <span class="token operator">:=</span> sync<span class="token punctuation">.</span>WaitGroup<span class="token punctuation">{</span><span class="token punctuation">}</span>

	<span class="token keyword">for</span> ng <span class="token operator">:=</span> <span class="token number">100</span><span class="token punctuation">;</span> ng <span class="token operator">&lt;=</span> <span class="token number">1000000</span><span class="token punctuation">;</span> ng <span class="token operator">*=</span> <span class="token number">10</span> <span class="token punctuation">{</span>
		b<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span>fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">&quot;#g-%d&quot;</span><span class="token punctuation">,</span> ng<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
			<span class="token comment">// 创建大量 goroutine，由于每次创建的 goroutine 会休眠</span>
			<span class="token comment">// 从而运行时不会复用正在休眠的 goroutine，进而不断创建新的 g</span>
			wg<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>ng<span class="token punctuation">)</span>
			<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> ng<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
				<span class="token keyword">go</span> <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
					time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span><span class="token number">100</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Millisecond<span class="token punctuation">)</span>
					wg<span class="token punctuation">.</span><span class="token function">Done</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
				<span class="token punctuation">}</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token punctuation">}</span>
			wg<span class="token punctuation">.</span><span class="token function">Wait</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

			<span class="token comment">// 现运行一次 GC 来提供一致的内存环境</span>
			runtime<span class="token punctuation">.</span><span class="token function">GC</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

			<span class="token comment">// 记录运行 b.N 次 GC 需要的时间</span>
			b<span class="token punctuation">.</span><span class="token function">ResetTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
				runtime<span class="token punctuation">.</span><span class="token function">GC</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
			<span class="token punctuation">}</span>
		<span class="token punctuation">}</span><span class="token punctuation">)</span>

	<span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>其结果可以通过如下指令来获得：</p> <div class="language-shell extra-class"><pre class="language-shell"><code>$ go <span class="token builtin class-name">test</span> -bench<span class="token operator">=</span>BenchmarkGCLargeGs -run<span class="token operator">=</span>^$ -count<span class="token operator">=</span><span class="token number">5</span> -v <span class="token builtin class-name">.</span> <span class="token operator">|</span> <span class="token function">tee</span> <span class="token number">4</span>.txt
$ benchstat <span class="token number">4</span>.txt
name                     time/op
GCLargeGs/<span class="token comment">#g-100-12       192µs ± 5%</span>
GCLargeGs/<span class="token comment">#g-1000-12      331µs ± 1%</span>
GCLargeGs/<span class="token comment">#g-10000-12    1.22ms ± 1%</span>
GCLargeGs/<span class="token comment">#g-100000-12   10.9ms ± 3%</span>
GCLargeGs/<span class="token comment">#g-1000000-12  32.5ms ± 4%</span>
</code></pre></div><p>这种情况通常发生于峰值流量后，大量 goroutine 由于任务等待被休眠，从而运行时不断创建新的 goroutine，
旧的 goroutine 由于休眠未被销毁且得不到复用，导致 GC 需要扫描的执行栈越来越多，进而完成 GC 所需的时间越来越长。
一个解决办法是使用 goroutine 池来限制创建的 goroutine 数量。</p> <h1 id="总结"><a href="#总结" class="header-anchor">#</a> 总结</h1> <p>GC 是一个复杂的系统工程，本文讨论的二十个问题尽管已经展现了一个相对全面的 Go GC。但它们仍然只是 GC 这一宏观问题的一些较为重要的部分，还有非常多的细枝末节、研究进展无法在有限的篇幅内完整讨论。</p> <p>从 Go 诞生之初，Go 团队就一直在对 GC 的表现进行实验与优化，但仍然有诸多未解决的问题，我们不妨对 GC 未来的改进拭目以待。</p> <h1 id="推荐阅读"><a href="#推荐阅读" class="header-anchor">#</a> 推荐阅读</h1> <p>【Why golang garbage-collector not implement Generational and Compact gc?】https://groups.google.com/forum/#!msg/golang-nuts/KJiyv2mV2pU/wdBUH1mHCAAJ</p> <p>【写一个内存分配器】http://dmitrysoshnikov.com/compilers/writing-a-memory-allocator/#more-3590</p> <p>【观察 GC】https://www.ardanlabs.com/blog/2019/05/garbage-collection-in-go-part2-gctraces.html</p> <p>【煎鱼 Go debug】https://segmentfault.com/a/1190000020255157</p> <p>【煎鱼 go tool trace】https://eddycjy.gitbook.io/golang/di-9-ke-gong-ju/go-tool-trace</p> <p>【trace 讲解】https://www.itcodemonkey.com/article/5419.html</p> <p>【An Introduction to go tool trace】https://about.sourcegraph.com/go/an-introduction-to-go-tool-trace-rhys-hiltner</p> <p>【http pprof 官方文档】https://golang.org/pkg/net/http/pprof/</p> <p>【runtime pprof 官方文档】https://golang.org/pkg/runtime/pprof/</p> <p>【trace 官方文档】https://golang.org/pkg/runtime/trace/</p></div> <footer class="page-edit"><!----> <div class="last-updated"><span class="prefix">上次更新:</span> <span class="time">1/29/2021, 9:31:30 AM</span></div></footer> <!----> </main></div><div class="global-ui"></div></div>
    <script src="/assets/js/app.cb35c8f6.js" defer></script><script src="/assets/js/2.063846a6.js" defer></script><script src="/assets/js/4.1ffb4609.js" defer></script><script src="/assets/js/6.29d112b1.js" defer></script>
  </body>
</html>
